2017-06-14 72 views
1

我需要下面的JSON格式轉換爲對象,我的類屬性轉換JSON來的OBJ C#

 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; 

       }); 

但我不能找到正確的信息 所以任何類型的幫助將是巨大 `

+0

可能重複[Newtonsoft.JSON無法使用TypeConverter屬性轉換模型](https://stackoverflow.com/questions/31325866/newtonsoft-json-cannot-convert-model-with-typeconverter-attribute)嘗試使用此方法一個轉換器 – Zinov

回答

2

最簡單的方法就是在你的JSON所有屬性創建類。 這裏有一個非常有用的工具:https://jsonutils.com/ 記得在picker中選擇JsonProperty。

然後,你可以使用:var object = JsonConvert.DeserializeObject<MainClass>(json);

最後,您可以使用對象LINQ查詢來獲取你所需要的訪問數據。

+0

我已經改變它{result = Newtonsoft.Json.JsonConvert.DeserializeObject (request,new Newtonsoft.Json.JsonSerializerSettings(){NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore});}但是你的答案確實有幫助,謝謝 –

+1

這很好。別客氣 ;) –