4

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?

Martin Plante
  • 4,553
  • 3
  • 33
  • 45

2 Answers2

6

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);
        }
    }
}
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
1

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
Ray Cheng
  • 12,230
  • 14
  • 74
  • 137