![](/img/trans.png)
[英]JSON.NET NullValueHandling in JsonPropertyAttribute not working as expected
[英]JSON.NET Conflicting property name when using JsonPropertyAttribute
我有以下JSON字符串:
{
"items" : "1",
"itemdetails":
[
{
"id" : "5",
"name:" "something"
}
]
}
items
表示項目計數,實際項目在itemdetails
。
我想反序列化為這樣的類:
class Parent
{
JsonProperty("itemdetails")]
public IEnumerable<Item> Items { get; set; }
}
class Item
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name {get; set; }
}
但是,當我打電話
JsonConvert.DeserializeObject<Parent>(inputString)
我得到一個JsonSerializationException
,字符串"1"
無法轉換為IEnumerable<Item>
。 我猜解析器嘗試反序列化items
從JSON到Items
的性質,因為它們的名稱相匹配。 並且它忽略了JsonProperty
屬性。
這是設計使然嗎? 任何解決方法? 謝謝!
編輯
正如Brian Rogers所說,此代碼可以正常工作。 我以為自己錯過了補充難題的機會。
問題是如果我要使用私有集合設置器並從構造函數中初始化那些屬性。
public Parent(IEnumerable<Item> items)
{
this.Items = items;
}
這導致引發異常。 我該怎么辦? 以某種方式注釋構造函數參數? 還是使用ConstructorHandling.AllowNonPublicDefaultConstructor
?
我看到兩個問題。 首先,您的JsonProperty
屬性格式錯誤。
你有:
JsonProperty("itemdetails"]
它應該是:
[JsonProperty("itemdetails")]
其次,您的JSON部分無效。
你有這個:
"name:" "something",
它應該是:
"name" : "something"
解決這兩個問題后,對我來說效果很好。 這是我使用的測試程序:
class Program
{
static void Main(string[] args)
{
string json = @"
{
""items"" : ""1"",
""itemdetails"":
[
{
""id"" : ""5"",
""name"" : ""something""
}
]
}";
Parent parent = JsonConvert.DeserializeObject<Parent>(json);
foreach (Item item in parent.Items)
{
Console.WriteLine(item.Name + " (" + item.Id + ")");
}
}
}
class Parent
{
[JsonProperty("itemdetails")]
public IEnumerable<Item> Items { get; set; }
}
class Item
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
輸出:
something (5)
編輯
好的,因此,如果我對您的理解正確,那么您真正的 Parent類實際上就是這樣:
class Parent
{
public Parent(IEnumerable<Item> items)
{
this.Items = items;
}
[JsonProperty("itemdetails")]
public IEnumerable<Item> Items { get; private set; }
}
在這種情況下,您有兩種選擇可以使其正常工作:
您可以在構造函數中更改參數名稱以匹配JSON,例如:
public Parent(IEnumerable<Item> itemdetails)
{
this.Items = itemdetails;
}
或者,您可以為Json.Net添加單獨的私有構造函數以使用:
class Parent
{
public Parent(IEnumerable<Item> items)
{
this.Items = items;
}
[JsonConstructor]
private Parent()
{
}
[JsonProperty("itemdetails")]
public IEnumerable<Item> Items { get; private set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.