1

I need to parse some JSON to objects in C#. I've looked at Newtonsoft and JavaScriptSerializer but either I don't know how to use them well or they do a poor job at handling format that could change and are awkward for complex structures. I want something where I can do something like:

JsonObject j = Deserialize(mystring);
String[] earthColors = j.maps["earth"].colors;

And not care about the rest of the structure.

Jason Robinson
  • 31,005
  • 19
  • 77
  • 131
Edwin Evans
  • 2,726
  • 5
  • 34
  • 47

2 Answers2

4

I think you should reconsider not using Json.Net

string mystring = 
    @"
    {
        ""maps"": {
            ""earth"": {
                ""colors"": [
                    ""blue"",
                    ""green""
                ]
            },
            ""moon"": {
                ""colors"": [
                    ""black"",
                    ""white""
                ]
            }
        }
    ";

dynamic j = JsonConvert.DeserializeObject(mystring);
foreach (var c in j.maps["earth"].colors)
{
    Console.WriteLine(c);
}
L.B
  • 114,136
  • 19
  • 178
  • 224
0

Static Class Approach

Here's a generic method for converting JSON to objects (be sure to include System.Web.Script.Serialization):

    public static T JsonToObject<T>(string JsonData)
    {
        // Deserialize the JSON into the object
        JavaScriptSerializer jss = new JavaScriptSerializer();
        T rf = (T)jss.Deserialize(JsonData, typeof(T));

        return rf;
    }

To convert an object back to JSON, use this general method:

    public static string ObjectToJson<T>(T rf)
    {
        // Serialize the object as JSON
        StringBuilder sb = new StringBuilder();
        JavaScriptSerializer jss = new JavaScriptSerializer();
        jss.Serialize(rf, sb);

        return sb.ToString();
    }

To use it, you simply create the class that matches the JSON response, then call the JsonToObject method.

JsonObject j = JsonToObject(mystring);

Dynamic Approach

For a more dynamic approach, you'll want to look at something like this:

JavaScriptSerializer jss = new JavaScriptSerializer();
var JsonObject = jss.Deserialize<dynamic>(mystring);

This will create the JsonObject dynamically, which you can then use Dictionary style accessors without necessarily needing to create the class up front. So, for the given JSON response

{ "maps": ["earth": {"colors": ["purple","chartreuse"] }] }

c class would be dynamically created that could be accessed as

JsonObject.maps["earth"].colors[0] == "purple";
JsonObject.maps["earth"].colors[1] == "chartreuse";
saluce
  • 13,035
  • 3
  • 50
  • 67
  • What do you mean by simply create the class that matches the JSON response. My concern is what if some new field is added or what if there are some portions of the JSON response that I don't care about? I don't want to make it any more brittle than it needs to be. – Edwin Evans May 18 '12 at 20:24
  • If a new field is added to the JSON response, you'll need to modify the `JsonObject` class to accomodate it (since this is not a dynamic approach). If there are fields in the JSON response you don't care about, you need not include those in your class. – saluce May 18 '12 at 21:46