[英]nested json c# object deserialization
我有以下json字符串(jsonString)
[
{
"name":"Fruits",
"references":[
{"stream":{"type":"reference","size":"original",id":"1"}},
],
"arts":[
{"stream":{"type":"art","size":"original","id":"4"}},
{"stream":{"type":"art","size":"medium","id":"9"}},
]
}
]
和以下C#對象
class Item
{
public string Name { get; set; }
public List<Stream> References { get; set; }
public List<Stream> Arts { get; set; }
public Item()
{
}
}
class Stream
{
public string Type { get; set; }
public string Size { get; set; }
public string Id { get; set; }
public Stream()
{
}
}
和以下代碼
Item item = JsonConvert.DeserializeObject<Item>(jsonString);
當我運行代碼時,它克隆了正確數量的引用和arts,但每個流都有null值(type = null,size = null)。
是否可以執行此json.net deserializeobject方法或應該手動反序列化?
編輯:好的,忽略以前的答案。 問題是你的數組(引用和藝術)包含反過來包含相關數據的對象。 基本上你有一層包裝太多了。 例如,這個JSON工作正常:
[
{
"name":"Fruits",
"references":[
{"Type":"reference","Size":"original","Id":"1"},
],
"arts":[
{"Type":"art","Size":"original","id":"4"},
{"type":"art","size":"medium","id":"9"},
]
}
]
如果您無法更改JSON,則可能需要在對象模型中引入新的包裝器類型:
public class StreamWrapper
{
public Stream Stream { get; set; }
}
然后使您的Item
類具有List<StreamWrapper>
變量而不是List<Stream>
。 這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.