Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to parse JSON response

Tags:

json

c#

asp.net

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.

like image 968
user788592 Avatar asked Dec 02 '15 12:12

user788592


People also ask

What are the methods to parse JSON?

parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Is JSON easy to parse?

JSON is a data interchange format that is easy to parse and generate. JSON is an extension of the syntax used to describe object data in JavaScript. Yet, it's not restricted to use with JavaScript. It has a text format that uses object and array structures for the portable representation of data.

How do I get JSON response?

To request JSON from a URL, you need to send an HTTP GET request to the server and provide the Accept: application/json request header with your request. The Accept header tells the server that our client is expecting JSON.

Is response JSON () Same as JSON parse?

The difference is: json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON. parse() is synchronous can parse a string to (a) JavaScript object(s).


2 Answers

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.)

like image 155
Patrick Hofman Avatar answered Oct 01 '22 00:10

Patrick Hofman


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

var ser = new System.Web.Script.Serialization.JavaScriptSerializer(); ser.DeserializeObject(json); 
like image 41
Łukasz Trzewik Avatar answered Oct 01 '22 01:10

Łukasz Trzewik