简体   繁体   English

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

[英]How to parse json object with variable key names using DataContractJsonSerializer

I intend to use DataContractJsonSerializer to convert the json i'm receiving to an object, but the keys in the root can have any name, something similar to this: 我打算使用DataContractJsonSerializer将我收到的json转换为一个对象,但是根中的键可以具有任何名称,类似于以下内容:

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

When the keys are fixed i can use [DataMember(Name = "keyname")] but in this case I don't know what to do. 当键固定后,我可以使用[DataMember(Name = "keyname")]但是在这种情况下,我不知道该怎么办。 Any ideas? 有任何想法吗?

Try this: 尝试这个:

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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用DataContractJsonSerializer来解析嵌套的json对象? - How to use DataContractJsonSerializer to parse a nested json object? 如何使用DataContractJsonSerializer解析包含混合基本类型的json对象数组? - How to parse a json object array containing mixed primitive types using DataContractJsonSerializer? 如何使用JSON.NET或DataContractJsonSerializer反序列化未类型化的对象 - How to deserialize an untyped object using JSON.NET or DataContractJsonSerializer Json使用DataContractJsonSerializer解析 - Json parse with DataContractJsonSerializer 使用DataContractJsonSerializer反序列化变量Type JSON数组 - Deserializing variable Type JSON array using DataContractJsonSerializer 如何获取JSON中的__type键以首先使用DataContractJsonSerializer - How to get the __type key in json to be first for DataContractJsonSerializer 无法使用DataContractJsonSerializer将对象序列化为JSON - Unable to Serialize Object to JSON Using DataContractJsonSerializer 使用DataContractJsonSerializer设置JSON对象root - Set JSON object root using DataContractJsonSerializer 使用DataContractJsonSerializer作为JSON数组序列化对象 - Serialize an object using DataContractJsonSerializer as a json array 使用 DataContractJsonSerializer 将字典序列化为 JSON 对象 - Serialize a Dictionary as JSON object using DataContractJsonSerializer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM