Home  >  Article  >  Backend Development  >  How to deserialize JSON to .NET object and select only one value from array using Newtonsoft json in C#?

How to deserialize JSON to .NET object and select only one value from array using Newtonsoft json in C#?

PHPz
PHPzforward
2023-08-31 18:37:021049browse

如何在 C# 中使用 Newtonsoft json 将 JSON 反序列化为 .NET 对象并从数组中仅选择一个值?

The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI.

The WebClient class uses the WebRequest class to provide access to resources. WebClient instances can access data using any WebRequest descendant registered through the WebRequest.RegisterPrefix method.

DownloadString downloads a string from a resource and returns a string.

If your request requires optional headers, you must add the headers to the Headers collection

Example

  • In the example below , we call the url "https://"jsonplaceholder.typicode.com/posts"

  • Then deserialize the example into a User array

  • From the user array we get to print the first array value

Example

class Program{
   static void Main(string[] args){
      var client = new WebClient();
      var json = client.DownloadString("https://jsonplaceholder.typicode.com/posts");
      var userPosts = JsonConvert.DeserializeObject<User[]>(json);
      System.Console.WriteLine(userPosts[0].title);
      Console.ReadLine();
   }
}
public class User{
   public string userId { get; set; }
   public string id { get; set; }
   public string title { get; set; }
   public string body { get; set; }
}

Output

sunt aut facere repellat provident occaecati excepturi optio reprehenderit

The above is the detailed content of How to deserialize JSON to .NET object and select only one value from array using Newtonsoft json in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete