So many people got this question like to deserialize any JSON string should we need to use Newtonsoft.Json.JsonConvert.DeserializeObject()or Newtonsoft.Json.Linq.JToken.Parse()method?? Let begin the explanation below…

Newtonsoft.Json uses LINQ-TO-JSON API internally to loop through the properties or objects in the given JSON string.

before understanding whether we need to use Newtonsoft.Json.JsonConvert.DeserializeObject()orNewtonsoft.Json.Linq.JToken.Parse() we need to know following some of the built-in classes.

JToken – This is the abstract base class.
JContainer – This is the abstract base class of JTokens that can contain other JTokens.
JArray – represents a JSON array (contains an ordered list of JTokens) having JSON starts with square brackets [ and ]
JObject – This is the class used to parse object which contains multiple JProperties having JSON starts with square brackets { and }.
JProperties – This is the class used to parse only properties whose value cannot be another property.
JValue – This is the class used to parse only values.

As we understand the internal classes which use by Newton.Json component, now coming to our question if you are pretty sure about your JSON string then we can use appropriate classes as mentioned above. But in case you are not about particular which classes need to be used for what kind of JSON properties use a Newtonsoft.Json.JsonConvert.DeserializeObject()method where it will take care of your JSON string and uses appropriate classes and parse it to the given object.

One more important point about this is If you don’t want complete JSON string to parse and you want only part or a particular set of properties or objects then suggested to go with Newtonsoft.Json.Linq as when we say Parse of these classes it won’t immediately converts (as it uses LINQ-to-JSON) instead it provides a Linq object where we can loop through and get only required properties information.

Following are the examples which demonstrate above explanations

Example-1: Using Linq classes directly

public string GetLastName(string jsonText)
{
//jsonText: {"EmplyeeFName": "Sai", "EmplyeeLName": "Kumar"}	
    JObject jResult = Newtonsoft.Json.Linq.JObject.Parse(jsonText);

    return (string)jResults["EmplyeeFName"];
}

Β Example-2: Using DeserializeObject

public string GetLastName(string jsonText)
{
//jsonText: {"EmplyeeFName": "Sai", "EmplyeeLName": "Kumar"}	
    dynamic jResult = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText);

    return (string)jResult.EmplyeeFName;
}

as you can see from the above examples, using DeserializeObject we can have typed properties.

Performance: I know this is the question everyone having like which methodology gives more performance and as per my observation and readings from different blogs both gives the same performance and which one to use is totally depends on your requirement.

Please comment your thoughts on this..

Happy Coding πŸ™‚