Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Deserializing JSON to .NET object using Newtonsoft json in C# and pick only one value from the array?
JSON deserialization is the process of converting JSON data into .NET objects. The Newtonsoft.Json library (also known as Json.NET) provides powerful methods to deserialize JSON strings into strongly-typed C# objects. When working with JSON arrays, you can easily pick specific values from the deserialized array.
Syntax
Following is the syntax for deserializing JSON to a .NET object −
T obj = JsonConvert.DeserializeObject<T>(jsonString);
For deserializing JSON arrays −
T[] objArray = JsonConvert.DeserializeObject<T[]>(jsonString);
Using WebClient to Fetch and Deserialize JSON
The WebClient class provides methods for downloading data from web resources. The DownloadString method downloads a string from a URI and returns it as a string, making it perfect for fetching JSON data from APIs.
Example
In this example, we fetch JSON data from a REST API, deserialize it to a User array, and pick the first element's title −
using System;
using System.Net;
using Newtonsoft.Json;
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);
Console.WriteLine("First post title: " + userPosts[0].title);
Console.WriteLine("Total posts: " + userPosts.Length);
}
}
public class User {
public string userId { get; set; }
public string id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
The output of the above code is −
First post title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit Total posts: 100
Picking Specific Values from JSON Arrays
Example
You can access any element in the deserialized array and extract specific properties −
using System;
using System.Net;
using Newtonsoft.Json;
using System.Linq;
class Program {
static void Main(string[] args) {
var client = new WebClient();
var json = client.DownloadString("https://jsonplaceholder.typicode.com/posts");
var userPosts = JsonConvert.DeserializeObject<Post[]>(json);
// Pick first post
Console.WriteLine("First post: " + userPosts[0].title);
// Pick last post
Console.WriteLine("Last post: " + userPosts[userPosts.Length - 1].title);
// Pick post by userId
var userOnePosts = userPosts.Where(p => p.userId == "1").ToArray();
Console.WriteLine("User 1 has " + userOnePosts.Length + " posts");
}
}
public class Post {
public string userId { get; set; }
public string id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
The output of the above code is −
First post: sunt aut facere repellat provident occaecati excepturi optio reprehenderit Last post: at nam consequatur ea labore ea harum User 1 has 10 posts
Using HttpClient (Modern Approach)
Example
For modern applications, HttpClient is preferred over WebClient as it provides better performance and async support −
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
class Program {
static async Task Main(string[] args) {
using (var client = new HttpClient()) {
var json = await client.GetStringAsync("https://jsonplaceholder.typicode.com/posts");
var posts = JsonConvert.DeserializeObject<Post[]>(json);
Console.WriteLine("Selected post: " + posts[4].title);
Console.WriteLine("Post ID: " + posts[4].id);
}
}
}
public class Post {
public int userId { get; set; }
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
The output of the above code is −
Selected post: nesciunt quas odio Post ID: 5
Conclusion
JSON deserialization with Newtonsoft.Json allows you to easily convert JSON arrays into strongly-typed C# objects. You can then access specific array elements using indexing or LINQ queries to extract the exact data you need from the deserialized objects.
