这让我发疯了...我正在使用 Json.net 将列表序列化为 JSON。我希望这个 JSON:
{
"fieldsets": [
{
"properties": [
{
"alias": "date",
"value": "2014-02-12T00:00:00"
},
{
"alias": "time",
"value": null
}
],
"alias": "eventDates",
"disabled": false
}
]
}
但相反,我得到这个:
{
"fieldsets": [
{
"properties": [
{
"values": [
{
"alias": "date",
"value": "2014-07-13T00:00:00"
},
{
"alias": "time",
"value": "Registration begins at 8:00 AM; walk begins at 9:00 AM"
}
]
}
],
"alias": "eventDates",
"disabled": false
}
]
}
我想要的"值"集合只是一个 JSON 数组,但我一生都无法弄清楚如何让它做到这一点。我的"属性"对象上有一个名为"值"的属性,所以我明白它为什么要这样做,但我只需要直数组,而不是 JSON 对象。
对于该响应,您需要此类结构
public class Property
{
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class Fieldset
{
[JsonProperty("properties")]
public Property[] Properties { get; set; }
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("disabled")]
public bool Disabled { get; set; }
}
public class Response
{
[JsonProperty("fieldsets")]
public Fieldset[] Fieldsets { get; set; }
}
这可能是答案:
public class Property
{
public string alias { get; set; }
public string value { get; set; }
}
public class Fieldset
{
public List<Property> properties { get; set; }
public string alias { get; set; }
public bool disabled { get; set; }
}
public class RootObject
{
public List<Fieldset> fieldsets { get; set; }
}
您可以转换为 JObject:
JObject jsonObject = JObject.Parse(myJsonString);
按键导航:
jsonObject["property"]["value"];//Property is value / object
jsonObject["value"];
按索引导航:
jsonObject[0]["value"]; // Property is array / list
jsonObject[0];