Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a JSON array using Json.Net

I'm working with Json.Net to parse an array. What I'm trying to do is to pull the name/value pairs out of the array and assign them to specific variables while parsing the JObject.

Here's what I've got in the array:

[   {     "General": "At this time we do not have any frequent support requests."   },   {     "Support": "For support inquires, please see our support page."   } ] 

And here's what I've got in the C#:

WebRequest objRequest = HttpWebRequest.Create(dest); WebResponse objResponse = objRequest.GetResponse(); using (StreamReader reader = new StreamReader(objResponse.GetResponseStream())) {     string json = reader.ReadToEnd();     JArray a = JArray.Parse(json);      //Here's where I'm stumped  } 

I'm fairly new to JSON and Json.Net, so it might be a basic solution for someone else. I basically just need to assign the name/value pairs in a foreach loop so that I can output the data on the front-end. Has anyone done this before?

like image 279
johngeek Avatar asked Mar 31 '13 04:03

johngeek


People also ask

Can you JSON parse an array?

Use the JSON. parse() method to pase a JSON array, e.g. JSON. parse(arr) . The method parses a JSON string and returns its JavaScript value or object equivalent.

What is JSON parse () method?

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.

What is JSON parsing example?

JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server's data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language.

How do you read Jobjects?

string json = DAO. getUploadDataSummary(); JObject uploadData = JObject. Parse(json); string array = (string)uploadData. SelectToken("d");


1 Answers

You can get at the data values like this:

string json = @" [      { ""General"" : ""At this time we do not have any frequent support requests."" },     { ""Support"" : ""For support inquires, please see our support page."" } ]";  JArray a = JArray.Parse(json);  foreach (JObject o in a.Children<JObject>()) {     foreach (JProperty p in o.Properties())     {         string name = p.Name;         string value = (string)p.Value;         Console.WriteLine(name + " -- " + value);     } } 

Fiddle: https://dotnetfiddle.net/uox4Vt

like image 157
Brian Rogers Avatar answered Oct 14 '22 17:10

Brian Rogers