C# 反序列化根 JSON 未知密钥 [英] C# Deserialize Root JSON Unknown Keys
问题描述
我有一个这样的 JSON 并且必须反序列化它:
<代码>{0":{"foo_id":"xyz","bar_id":"abc",书": {0":{"title":"你好",作者":person_x"},1":{"title":"你好",作者":person_y"}},1":{"foo_id":"xyz","bar_id":"abc",书": {0":{"title":"你好",作者":person_a"},1":{"title":"再见",作者":person_b"}},"随机":"字符串","其他":"东西"}
类似于
更新:
由于您更改了问题中的原始 JSON,因此可以将第二个给定的 JSON 反序列化:
班级:
公共类RootObject{[JsonExtensionData]公共字典项目{得到;放;}[JsonProperty(随机")]公共字符串随机{获取;放;}[JsonProperty(其他")]公共字符串其他{得到;放;}}
反序列化:
var 结果 = JsonConvert.DeserializeObject(json);
I have a JSON like this and have to deserialize it:
{
"0": {
"foo_id":"xyz",
"bar_id":"abc",
"book": {
"0": {
"title":"hello",
"author":"person_x"
},
"1": {
"title":"hi",
"author":"person_y"
}
},
"1": {
"foo_id":"xyz",
"bar_id":"abc",
"book": {
"0": {
"title":"hello",
"author":"person_a"
},
"1": {
"title":"bye",
"author":"person_b"
}
},
"random":"string",
"other":"thing"
}
Similar to this question, except the answer given doesn't work, because I don't have the luxury of creating a class like this
public class RootObject
{
public Dictionary<string, Object> Objects {get; set;}
}
If I do than the Objects field is null after deserialization.
Both the root object and book object are dynamic.
Any other approaches would be appreciated, Thanks in advance.
Because the JSON you have does not contains a RootObject
that holds a dictionary, you can deserialize straight into a Dictionary
like so:
Class:
public class Item
{
[JsonProperty("foo_id")]
public string FooId { get; set; }
[JsonProperty("bar_id")]
public string BarId { get; set; }
}
Deserialize:
var result = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);
Result:
Update:
Since you have changed the original JSON in your question, the second given JSON can be deserialized as so:
Class:
public class RootObject
{
[JsonExtensionData]
public Dictionary<string, JToken> Items { get; set; }
[JsonProperty("random")]
public string Random { get; set; }
[JsonProperty("other")]
public string Other { get; set; }
}
Deserialize:
var result = JsonConvert.DeserializeObject<RootObject>(json);
这篇关于C# 反序列化根 JSON 未知密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!