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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Follow these steps:
- Convert your JSON to C# using json2csharp.com;
- Create a class file and put the above generated code in there;
- Add the
Newtonsoft.Json
library to your project using the Nuget Package Manager; -
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.)
Method 2
You can safely use built-in JavaScriptSerializer
without referencing additional third party libraries:
var ser = new System.Web.Script.Serialization.JavaScriptSerializer(); ser.DeserializeObject(json);
Method 3
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 }
Method 4
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);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0