What is the simplest C# function to parse a JSON string into an object? [closed]
What is the simplest C# function to parse a JSON string into a object and display it (C# XAML WPF)? (for example object with 2 arrays - arrA and arrB)
Solution 1:
Just use the Json.NET library. It lets you parse Json format strings very easily:
JObject o = JObject.Parse(@"
{
""something"":""value"",
""jagged"":
{
""someother"":""value2""
}
}");
string something = (string)o["something"];
Documentation: Parsing JSON Object using JObject.Parse
Solution 2:
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(YourObjectType));
YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream);
You could also use the JavaScriptSerializer
, but DataContractJsonSerializer
is supposedly better able to handle complex types.
Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use DataContractJsonSerializer
since it is hard baked for WCF.
Solution 3:
I think this is what you want:
JavaScriptSerializer JSS = new JavaScriptSerializer();
T obj = JSS.Deserialize<T>(String);
Solution 4:
You should create a structure that represents JSON keys (in case if you exactly know it) and then you can easily deserialize JSON string into your structure. In my examle I've deserialized a response from Google Cloud Message server:
class templateResponse
{
public String multicast_id;
public String success;
public String failure;
public String canonical_ids;
public Result[] results;
public class Result
{
public String message_id;
public String registration_id;
public String error;
};
}
incoming JSON was:
"\"multicast_id\":7400896764380883211,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1351777805148960%39895cf0f9fd7ecd\"}]}"
So, use
templateResponse result = new JavaScriptSerializer().Deserialize<templateResponse>(json);
and you will get deserialized result
object