How to Deserializing JSON to .NET object using Newtonsoft json in C# and pick only one value from the array?


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 with any WebRequest descendant registered with the WebRequest.RegisterPrefix method.

DownloadString Downloads a String from a resource and returns a String.

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

Example

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

  • The example is then deserialized to User array

  • From the user array we are printing 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

Updated on: 05-Nov-2020

442 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements