How to read JSON with object name using Json.Net in C#

Introduction:
In this article I am going to explain how to read the values from Json using Json.Net library when it is having Object Name.

Description:

In this article we are using Json.Net library to parse and read values in Json. We will be using JSON serializer methods available in this dictionary.

If you don’t have Json Framework in your machine you can get it from Nugget for Json.

Sample JSon file which we use in this article

{"employees":[
{"firstName":"Test1FN", "lastName":"Test1LN"},
{"firstName":"Test2FN", "lastName":"Test2LN"}
]}

Implementation:

After adding library to your project ensure that you have added the namespace reference in your page

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Next add a class to hold the values, note that I have used JsonProperty to map the JSON property to a .NET member or constructor parameter. This is very important as the object name format is not following key: value combination so if you don’t set this then while reading you will get exception.

[JsonObject(MemberSerialization.OptIn)]
public class User
{
   [JsonProperty("firstName", Required = Required.Always)]
   public string FirstName { get; set; }

   [JsonProperty("lastName", Required = Required.Always)]
   public string LastName { get; set; }
}

Now you can use the below code to read the values

//Load your Json string here
String jsonString = "{\"user\":[{\"firstName\": \"Test1FN\", \"lastName\": \"Doe\"},{\"firstName\": \"Test2FN\", \"lastName\": \"Test2LN\"}]}";
JToken root = JObject.Parse(jsonString);
JToken user = root["user"];
//Deserialize the Json to list
var deserializedUser = JsonConvert.DeserializeObject<List<User>>(user.ToString());

//Loop through values 
foreach (User p in deserializedUser)
{
//Your code to process the values
}
Advertisements

, , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: