Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JObject.Parse vs JsonConvert.DeserializeObject

What's the difference between JsonConvert.DeserializeObject and JObject.Parse? As far as I can tell, both take a string and are in the Json.NET library. What kind of situation would make one more convenient than the other, or is it mainly just preference?

For reference, here's an example of me using both to do exactly the same thing - parse a Json string and return a list of one of the Json attributes.

public ActionResult ReadJson() {     string countiesJson = "{'Everything':[{'county_name':null,'description':null,'feat_class':'Civil','feature_id':'36865',"                     +"'fips_class':'H1','fips_county_cd':'1','full_county_name':null,'link_title':null,'url':'http://www.alachuacounty.us/','name':'Alachua County'"+ ",'primary_latitude':'29.7','primary_longitude':'-82.33','state_abbreviation':'FL','state_name':'Florida'},"+                     "{'county_name':null,'description':null,"+ "'feat_class':'Civil','feature_id':'36866','fips_class':'H1','fips_county_cd':'3','full_county_name':null,'link_title':null,'url':'http://www.bakercountyfl.org/','name':'Baker County','primary_latitude':'30.33','primary_longitude':'-82.29','state_abbreviation':'FL','state_name':'Florida'}]}";      //Can use either JSONParseObject or JSONParseDynamic here     List<string> counties = JSONParseObject(countiesJson);     JSONParseDynamic(countiesJson);     return View(counties); }  public List<string> JSONParseObject(string jsonText) {     JObject jResults = JObject.Parse(jsonText);     List<string> counties = new List<string>();     foreach (var county in jResults["Everything"])     {         counties.Add((string)county["name"]);     }     return counties; }  public List<string> JSONParseDynamic(string jsonText) {     dynamic jResults = JsonConvert.DeserializeObject(jsonText);     List<string> counties = new List<string>();     foreach(var county in jResults.Everything)     {         counties.Add((string)county.name);     }     return counties; } 
like image 300
hubatish Avatar asked May 14 '14 03:05

hubatish


People also ask

What is JsonConvert DeserializeObject?

DeserializeObject(String, Type,JsonConverter[]) Deserializes the JSON to the specified . NET type using a collection of JsonConverter. DeserializeObject(String, Type, JsonSerializerSettings) Deserializes the JSON to the specified .

What is the difference between JToken and JObject?

JToken is the base class for all JSON elements. You should just use the Parse method for the type of element you expect to have in the string. If you don't know what it is, use JToken, and then you'll be able to down cast it to JObject, JArray, etc. In this case you always expect a JObject, so use that.

What does JObject parse do?

Parse() is a JObject class method. This parse method is used to parse a JSON string into a C# object. It parses the data of string based on its key value. This key value is then used to retrieve the data.


1 Answers

The LINQ-to-JSON API (JObject, JToken, etc.) exists to allow working with JSON without needing to know its structure ahead of time. You can deserialize any arbitrary JSON using JToken.Parse, then examine and manipulate its contents using other JToken methods. LINQ-to-JSON also works well if you just need one or two values from the JSON (such as the name of a county).

JsonConvert.DeserializeObject, on the other hand, is mainly intended to be used when you DO know the structure of the JSON ahead of time and you want to deserialize into strongly typed classes. For example, here's how you would get the full set of county data from your JSON into a list of County objects.

class Program {     static void Main(string[] args)     {         string countiesJson = "{'Everything':[{'county_name':null,'description':null,'feat_class':'Civil','feature_id':'36865',"                 +"'fips_class':'H1','fips_county_cd':'1','full_county_name':null,'link_title':null,'url':'http://www.alachuacounty.us/','name':'Alachua County'"+ ",'primary_latitude':'29.7','primary_longitude':'-82.33','state_abbreviation':'FL','state_name':'Florida'},"+                 "{'county_name':null,'description':null,"+ "'feat_class':'Civil','feature_id':'36866','fips_class':'H1','fips_county_cd':'3','full_county_name':null,'link_title':null,'url':'http://www.bakercountyfl.org/','name':'Baker County','primary_latitude':'30.33','primary_longitude':'-82.29','state_abbreviation':'FL','state_name':'Florida'}]}";          foreach (County c in JsonParseCounties(countiesJson))         {             Console.WriteLine(string.Format("{0}, {1} ({2},{3})", c.name,                 c.state_abbreviation, c.primary_latitude, c.primary_longitude));         }     }      public static List<County> JsonParseCounties(string jsonText)     {         return JsonConvert.DeserializeObject<RootObject>(jsonText).Counties;     } }  public class RootObject {     [JsonProperty("Everything")]     public List<County> Counties { get; set; } }  public class County {     public string county_name { get; set; }     public string description { get; set; }     public string feat_class { get; set; }     public string feature_id { get; set; }     public string fips_class { get; set; }     public string fips_county_cd { get; set; }     public string full_county_name { get; set; }     public string link_title { get; set; }     public string url { get; set; }     public string name { get; set; }     public string primary_latitude { get; set; }     public string primary_longitude { get; set; }     public string state_abbreviation { get; set; }     public string state_name { get; set; } } 

Notice that Json.Net uses the type argument given to the JsonConvert.DeserializeObject method to determine what type of object to create.

Of course, if you don't specify a type when you call DeserializeObject, or you use object or dynamic, then Json.Net has no choice but to deserialize into a JObject. (You can see for yourself that your dynamic variable actually holds a JObject by checking jResults.GetType().FullName.) So in that case, there's not much difference between JsonConvert.DeserializeObject and JToken.Parse; either will give you the same result.

like image 168
Brian Rogers Avatar answered Sep 28 '22 02:09

Brian Rogers