JObject.Parse VS JsonConvert.DeserializeObject [英] JObject.Parse vs JsonConvert.DeserializeObject

查看:172
本文介绍了JObject.Parse VS JsonConvert.DeserializeObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么JsonConvert.DeserializeObject和JObject.Parse之间的区别?至于我可以告诉大家,无论是采取一个字符串,并在Json.NET库。什么样的情况会令其中一个比另一个更方便,或者是它主要只是preference?

有关参考,在这里是同时使用做同样的事情我的一个例子 - 解析一个JSON字符串,返回的JSON的属性之一名单。

 公众的ActionResult ReadJson()
{
    字符串countiesJson ={一切:[{COUNTY_NAME':空,说明:空,feat_class':'公民','feature_id':'36865'。
                    +\"'fips_class':'H1','fips_county_cd':'1','full_county_name':null,'link_title':null,'url':'http://www.alachuacounty.us/','name':'Alachua县'+ \",'primary_latitude':'29.7','primary_longitude':'-82.33','state_abbreviation':'FL','state_name':'Florida'},\"+
                    {'COUNTY_NAME':空,说明:空,+ \"'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'}]}\";    //可以使用JSONParseObject或JSONParseDynamic这里
    清单<串GT;县= JSONParseObject(countiesJson);
    JSONParseDynamic(countiesJson);
    返回查看(县);
}公开名单<串GT; JSONParseObject(字符串jsonText)
{
    JObject jResults = JObject.Parse(jsonText);
    清单<串GT;县=新的List<串GT;();
    的foreach(在jResults VAR县[一切])
    {
        counties.Add((串)县[名称]);
    }
    回到县;
}公开名单<串GT; JSONParseDynamic(字符串jsonText)
{
    动态jResults = JsonConvert.DeserializeObject(jsonText);
    清单<串GT;县=新的List<串GT;();
    的foreach(在jResults.Everything VAR县)
    {
        counties.Add((字符串)county.name);
    }
    回到县;
}


解决方案

的LINQ到JSON API( JObject JToken 等)存在允许使用JSON工作,而无需提前了解它的结构。您可以使用反序列化任意JSON JToken.Parse ,然后检查并使用其它 JToken 方法操纵它的内容。 LINQ到JSON也是行之有效的,如果你只需要一个或两个值从JSON(如县的名称)。

JsonConvert.DeserializeObject ,而另一方面,主要是打算当你知道了JSON提前的结构,使用,要反序列化为强烈类型类。例如,这里是你如何获得全套县数据从您的JSON到对象的列表。

 类节目
{
    静态无效的主要(字串[] args)
    {
        字符串countiesJson ={一切:[{COUNTY_NAME':空,说明:空,feat_class':'公民','feature_id':'36865'。
                +\"'fips_class':'H1','fips_county_cd':'1','full_county_name':null,'link_title':null,'url':'http://www.alachuacounty.us/','name':'Alachua县'+ \",'primary_latitude':'29.7','primary_longitude':'-82.33','state_abbreviation':'FL','state_name':'Florida'},\"+
                {'COUNTY_NAME':空,说明:空,+ \"'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(在JsonParseCounties(countiesJson县c)条)
        {
            Console.WriteLine(的String.Format({0},{1}({2},{3}),c.name,
               c.state_abbreviation,c.primary_latitude,c.primary_longitude));
        }
    }    公共静态列表<&县GT; JsonParseCounties(字符串jsonText)
    {
        返回JsonConvert.DeserializeObject< RootObject>(jsonText).Counties;
    }
}公共类RootObject
{
    [JsonProperty(一切)]
    公开名单<&县GT;县{搞定;组; }
}公共类县
{
    公共字符串COUNTY_NAME {搞定;组; }
    公共字符串描述{搞定;组; }
    公共字符串feat_class {搞定;组; }
    公共字符串feature_id {搞定;组; }
    公共字符串fips_class {搞定;组; }
    公共字符串fips_county_cd {搞定;组; }
    公共字符串full_county_name {搞定;组; }
    公共字符串LINK_TITLE {搞定;组; }
    公共字符串URL {搞定;组; }
    公共字符串名称{;组; }
    公共字符串primary_latitude {搞定;组; }
    公共字符串primary_longitude {搞定;组; }
    公共字符串STATE_ABBREVIATION {搞定;组; }
    公共字符串STATE_NAME {搞定;组; }
}

注意Json.Net使用给予 JsonConvert.DeserializeObject 方法的类型参数来决定要创建的对象的类型。

当然,如果你当你调用 DeserializeObject ,不指定类型或使用对象动态,然后Json.Net别无选择,只能反序列化到一个 JObject 。 (您可以看到自己的动态变量实际上通过检查持有 JObject jResults.GetType()。全名。 )所以在这种情况下,有没有太大差别 JsonConvert.DeserializeObject JToken.Parse ;要么会给你同样的结果。

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;
}

解决方案

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.

这篇关于JObject.Parse VS JsonConvert.DeserializeObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆