如何使用DataContractJsonSerializer解析具有可变键名的json对象

时间:2018-07-31 20:33:34

标签: c# json

我打算使用DataContractJsonSerializer将我收到的json转换为对象,但是根中的键可以具有任何名称,类似于以下内容:

{
"Jhon": {...},
"Lucy": {...},
"Robert": {...}
...
}

固定键后,我可以使用[DataMember(Name = "keyname")],但是在这种情况下,我不知道该怎么办。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

尝试一下:

var serializer = new DataContractJsonSerializer(typeof(RootObject), new DataContractJsonSerializerSettings()
{
    UseSimpleDictionaryFormat = true
});

var json = @"{
""Jhon"": { ""Name"": ""John""},
""Lucy"": {},
""Robert"": {}
}";
var bytes = Encoding.UTF8.GetBytes(json);
using (var stream = new MemoryStream(bytes))
{
    var results = serializer.ReadObject(stream);
}

// Define other methods and classes here
public class RootObject : Dictionary<string, User>
{
}
public class User
{
    public string Name { get; set; }
}