【问题标题】:Converting Json To Obj C#将 Json 转换为 Obj C#
【发布时间】:2017-06-14 16:12:18
【问题描述】:

我需要将下面的 JSON 格式转换为一个对象,我的 Class 属性是

        public string address_line_1 { get; set; }
        public string locality { get; set; }
        public string region { get; set; }
        public string permises { get; set; }
        public string postal_code { get; set; }

我得到的 JSON 是

 {  
   "items_per_page":2,
   "items":[  
      {  
         "title":"Info",
         "description":"02506398 -  ",
         "links":{  
            "self":"/company/02506398"
         },
         "company_number":"11111",
         "company_status":"active",
         "address":{  
            "region":"Somewhere  ,",
            "postal_code":"TX1 7JQ",
            "locality":"Somewhere  , Somewhere  Mill",
            "premises":"Somewhere  House",
            "address_line_1":"Somewhere  Road"
         },
         "matches":{  
            "snippet":[  

            ],
            "title":[  
               1,
               7,
               9,
               12
            ]
         },
         "description_identifier":[  
            "incorporated-on"
         ],
         "kind":"searchresults#company",
         "date_of_creation":"1990-05-29",
         "company_type":"ltd",
         "snippet":"",
         "address_snippet":"Somewhere  House, Somewhere  Road, Somewhere  , Somewhere  Mill, Somewhere  ,, TX1 7JQ"
      },
      {  


}

我需要得到的唯一信息是 地址部分,我尝试过 下面的代码

dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(t, new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore });

或者

Newtonsoft.Json.JsonConvert.DeserializeObject<List<Address>>(t).ForEach(cc =>
                {
                    newAddress.address_line_1 = cc.address_line_1;
                    newAddress.locality = cc.locality;
                    newAddress.permises = cc.permises;
                    newAddress.region = cc.region;
                    newAddress.postal_code = cc.postal_code;

                });

但我找不到正确的信息 所以任何类型的帮助都会很棒 `

【问题讨论】:

标签: c# json json.net


【解决方案1】:

最简单的方法是为 JSON 中的所有属性创建类。 有一个非常有用的工具:https://jsonutils.com/ 记得在picker中选择JsonProperty。

然后,您可以使用:var object = JsonConvert.DeserializeObject&lt;MainClass&gt;(json);

最后,您可以在对象上使用 LINQ 查询来访问您的数据,以获得您需要的数据。

【讨论】:

  • 我已将其更改为 {result = Newtonsoft.Json.JsonConvert.DeserializeObject(request, new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }); } 但你的回答确实有帮助,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-08
相关资源
最近更新 更多