简体   繁体   English

反序列化包含动态属性 JSON.NET 的 object

[英]Deseralize an object that contain dynamic properties JSON.NET

how to deserialize this?如何反序列化这个? PS: dynamic1,dynamic2,etc.. each one has totally different name PS:dynamic1,dynamic2等。每个都有完全不同的名称

JSON: JSON:

"bob": {
    "dynamic1": 1,
    "dynamic2": 5,
    "dynamic3": 9,
},

 public class Bob
 {     
        [JsonProperty("bob")]
        public string Name{ get; set; }
 }

public class Root
{

        [JsonProperty(PropertyName = "data")]
        public Dictionary<Bob, int> DataItems { get; set; }
}
var resultJSON = JsonConvert.DeserializeObject<Root>(json);

Your class Bob does not correctly represent the data you have in your JSON.您的 class Bob不能正确地表示您在 JSON 中的数据。 Your json shows Bob to be an object in your class, your Jsonproperty defines bob as a string.您的 json 显示Bob在您的 class 中是 object,您的Jsonpropertybob定义为字符串。

For your JSON:对于您的 JSON:

{
  "bob": {
    "dynamic1": 1,
    "dynamic2": 5,
    "dynamic3": 9,
  }
}

you should use the RootObject Class the following way to properly deserialize your JSON,您应该使用RootObject Class 以下方式正确反序列化您的 JSON,

public class RootObject {
    [JsonProperty("bob")]
    public Dictionary<string, int> Bob { get; set; }
}

// and in your main, use the following to deserialize
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);

In the above example, obj has a Dictionary containing dynamic1 , dynamic2 and dynamic3 as Keys and 1, 5, and 9 as the respective values.在上面的示例中, obj 有一个 Dictionary 包含dynamic1dynamic2dynamic3作为键和 1、5 和 9 作为各自的值。

PS: When you deserialize the json into your class, the JsonProperty must exactly match the property in the JSON itself. PS:当您将 json 反序列化为 class 时, JsonProperty必须与 JSON 本身的属性完全匹配。 If you use [JsonProperty("Bob")] with capital B and you have lowercase in json, it wont work.如果您使用带有大写 B 的[JsonProperty("Bob")]并且您在 json 中使用小写字母,则它将不起作用。 JSON is case sensetive as well. JSON 也是区分大小写的。

Why not use dynamic :为什么不使用动态

dynamic obj = JsonConvert.DeserializeObject(json);
int dynamic1 = obj.dynamic1;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM