如何使用动态属性名称反序列化JSON对象?
问题描述:
这是来自远程服务器的JSON....如何为此创建C#对象?
Here is my JSON from a remote server....how do I create a C# object for this?
{
"payload":
{
"one":
{
"x": 1
},
"two":
{
"x": 2
},
"three":
{
"x": 3
}
}
}
http://json2csharp.com/创建了三个类型为一个",两个"和三个"的类"...但是这些都是动态值.在下一个请求中,我可能会得到四个",五个",六个"
http://json2csharp.com/ created three classes of type "one", "two" and "three"...but these are dynamic values. I may get "four", "five", "six" on the next request
答
您可以使用Dictionary<string,YourClass>
string json = @"{ ""payload"": { ""one"": { ""x"":1 }, ""two"": { ""x"":2 }, ""three"": { ""x"":3 } } }";
var root = JsonConvert.DeserializeObject<RootObject>(json);
public class Item
{
public int x { get; set; }
}
public class RootObject
{
public Dictionary<string,Item> payload { get; set; }
}