Easiest way to parse JSON response

Is there any easy way to parse below JSOn in c#

{"type":"text","totalprice":"0.0045","totalgsm":"1","remaincredit":"44.92293","messages": [
{"status":"1","messageid":"234011120530636881","gsm":"923122699633"}
]}

and in case Multiple results.


Follow these steps:

  1. Convert your JSON to C# using json2csharp.com;
  2. Create a class file and put the above generated code in there;
  3. Add the Newtonsoft.Json library to your project using the Nuget Package Manager;
  4. Convert the JSON received from your service using this code:

     RootObject r = JsonConvert.DeserializeObject<RootObject>(json);
    

(Feel free to rename RootObject to something more meaningful to you. The other classes should remain unchanged.)


You can safely use built-in JavaScriptSerializer without referencing additional third party libraries:

var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
ser.DeserializeObject(json);

I found a way to get it without using any external API

        using (var w = new WebClient())
        {
            var json_data = string.Empty;
            string url = "YOUR URL";
            // attempt to download JSON data as a string
            try
            {
                json_data = w.DownloadString(url);
                JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                var result = jsSerializer.DeserializeObject(json_data);
                Dictionary<string, object> obj2 = new Dictionary<string, object>();
                obj2=(Dictionary<string,object>)(result);

                string val=obj2["KEYNAME"].ToString();
            }
            catch (Exception) { }
            // if string with JSON data is not empty, deserialize it to class and return its instance 
        }

For me ... the easiest way to do that is using JSON.net do a deserialize to a entity that represents the object, for example:

public class Message
{
    public string status { get; set; }
    public string messageid { get; set; }
    public string gsm { get; set; }
}

public class YourRootEntity
{
    public string type { get; set; }
    public string totalprice { get; set; }
    public string totalgsm { get; set; }
    public string remaincredit { get; set; }
    public List<Message> messages { get; set; }
}

And do this:

YourRootEntity data JsonConvert.DeserializeObject<YourRootEntity>(jsonStrong);