How can I deserialize a JSON object that uses unspecified and variable property names

流过昼夜 提交于 2019-12-10 11:19:35

问题


I have a JSON response (which I have no control over) similar to this:

{"response":{
  "a" : "value of a",
  "b" : "value of b",
  "c" : "value of c",
  ...
}}

Where:

  • "a", "b", "c" are unknown names upfront.
  • The number of items can vary.

All I need at the end is an array of strings for all the values. Keeping the names is a bonus (Dictionary?) but I need to browse values by the order in which they appear.

How would you achieve this using JSON.NET?


回答1:


You can use the JObject class from the Newtonsoft.Json.Linq namespace to deserialize the object into a DOM-like structure:

public class StackOverflow_10608188
{
    public static void Test()
    {
        string json = @"{""response"":{
          ""a"" : ""value of a"",
          ""b"" : ""value of b"",
          ""c"" : ""value of c""
        }}";
        JObject jo = JObject.Parse(json);
        foreach (JProperty property in jo["response"].Children())
        {
            Console.WriteLine(property.Value);
        }
    }
}



回答2:


This works but not very pretty. I believe you can exchange to json.net with JavaScriptSerializer.

var json = "{\"response\":{\"a\":\"value of a\",\"b\":\"value of b\",\"c\":\"value of c\"}}";
var x = new System.Web.Script.Serialization.JavaScriptSerializer();
var res = x.Deserialize<IDictionary<string, IDictionary<string, string>>>(json);

foreach (var key in res.Keys)
{
    foreach (var subkey in res[key].Keys)
    {
        Console.WriteLine(res[key][subkey]);
    }
}

or

Console.WriteLine(res["response"]["a"]);
Console.WriteLine(res["response"]["b"]);
Console.WriteLine(res["response"]["c"]);

output:

value of a
value of b
value of c


来源:https://stackoverflow.com/questions/10608188/how-can-i-deserialize-a-json-object-that-uses-unspecified-and-variable-property

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