JSON.NET: Deserializing part of a JSON object to a dictionary

▼魔方 西西 提交于 2019-12-09 18:27:47

问题


I have JSON like this:

{
   "Property":"Blah blah",
   "Dictionary": {
        "Key1" : "Value1",
        "Key2" : "Value2",
        "Key3" : "Value3"
   }
}

I want to extract the "Dictionary" object as a Dictionary (so it'd be like Key1 => Value1, etc.). If I just had the "Dictionary" object directly, I could use:

 JsonConvert.DeserializeObject<Dictionary<string, string>>

What's the best way to get just the Dictionary property as a Dictionary?

Thanks in advance! Tim


回答1:


Took me a little while to figure out, but I just didn't feel great about using string parsing or regexes to get at the inner JSON that I want.

Simple enough; I did something along these lines to get at the inner data:

var jObj = JObject.Parse(jsonText);
var innerJObj = JObject.FromObject(jObj["Dictionary"]);

Works well enough.




回答2:


I think you'd have to parse the JSON and remove the outer object. You can dictate what kind of object you are deserializing to, but there is no way to tell it NOT to deserialize the outermost object.




回答3:


You could also define the property as Dictionary in a class.

 var str = @"{
   ""Property"":""Blah blah"",
   ""Dictionary"": {
       ""Key1"" : ""Value1"",
       ""Key2"" : ""Value2"",
       ""Key3"" : ""Value3""
   }
 }";

 class MyObject {
   string Property { get; set; }
   Dictionary<string, string> Dictionary { get; set; }
 }

 MyObject obj = JsonConvert.DeserializeObject<MyObject>(str);
 var dict = obj.Dictionary;



回答4:


For reference, your answer is to (de)serialize json fragments. Also answered here, but your solution looks more succinct. Curious about performance differences...



来源:https://stackoverflow.com/questions/4035230/json-net-deserializing-part-of-a-json-object-to-a-dictionary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!