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";