2016-10-21 90 views
2

我有一個JSON像下面,轉換JSON數組到C#對象集合

[ 
    { 
    "document": 
      { 
       "createdDate":1476996267864, 
       "processedDate":1476996267864, 
       "taxYear":"2015", 
       "type":"user_document" 
      } 
    }, 
    { 
    "document": 
      { 
       "createdDate":1476998303463, 
       "processedDate":0, 
       "taxYear":"2015", 
       "type":"user_document" 
      } 
    } 
    ] 

我需要將其轉換爲C#對象。我的對象類型是如下─

public class UserDocument 
    { 
     [JsonProperty(PropertyName = "type")] 
     public string type { get; set; } 

     [JsonProperty(PropertyName = "taxYear")] 
     public string taxYear { get; set; } 

     [JsonProperty(PropertyName = "createdDate")] 
     public string createdDate { get; set; } 

     [JsonProperty(PropertyName = "processedDate")] 
     public string processedDate { get; set; } 

    } 

我用下面的代碼進行反序列化JSON的,但所有UserDocument中屬性爲null

var test = JsonConvert.DeserializeObject<List<UserDocument>>(jsonString); 

爲什麼我收到的所有UserDocument中屬性爲null,什麼是錯在這裏?我沒有收到任何錯誤。

你也可以建議一個很好的例子,讓CouchBase queryresult進入.net對象。

+0

'processedDate'和'createdDate'不是字符串。 – RhinoDevel

+0

可能的重複http://stackoverflow.com/questions/4611031/convert-json-string-to-c-sharp-object –

+0

你的json是錯的 – Mostafiz

回答

4

似乎你的json格式不正確。如果我說你的JSON是像

[ 
    "document": 
      { 
       "createdDate":1476996267864, 
       "processedDate":1476996267864, 
       "taxYear":"2015", 
       "type":"user_document" 
      }, 

    "document": 
      { 
       "createdDate":1476998303463, 
       "processedDate":0, 
       "taxYear":"2015", 
       "type":"user_document" 
      } 
    ] 

然後創建

public class Document 
{ 
    public UserDocument document {get;set;} 
} 

模型,並改變你的UserDocument模型createdDateprocessedDate性質爲double,因爲它就像在你的JSON

public class UserDocument 
    { 
     [JsonProperty(PropertyName = "type")] 
     public string type { get; set; } 

     [JsonProperty(PropertyName = "taxYear")] 
     public string taxYear { get; set; } 

     [JsonProperty(PropertyName = "createdDate")] 
     public double createdDate { get; set; } 

     [JsonProperty(PropertyName = "processedDate")] 
     public double processedDate { get; set; } 

    } 

然後反序列化

var test = JsonConvert.DeserializeObject<List<Document>>(jsonString); 
+0

您也可以將屬性添加到'UserDocument'類中,該類將'createdDate'和'processedDate'屬性作爲'DateTime'值返回。 – krillgar

+0

@Mostafiz - 它的作品,非常感謝! – blue

+0

@krillgar這些都不是實際的日期時間類型,他們是utc等價日期的雙倍值 – Mostafiz

1

這樣的事情(使用Newtonsoft.Json.Linq):

var documents = JArray.Parse(json).Select(t => t["document"].ToObject<UserDocument>());

+0

這workds – blue