Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert json to a C# array?

Does anyone know how to convert a string which contains json into a C# array. I have this which reads the text/json from a webBrowser and stores it into a string.

string docText = webBrowser1.Document.Body.InnerText; 

Just need to somehow change that json string into an array. Been looking at Json.NET but I'm not sure if that's what I need, as I don't want to change an array into json; but the other way around. Thanks for the help!

like image 492
Joey Morani Avatar asked Mar 06 '12 15:03

Joey Morani


People also ask

What is JSON C#?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is language-independent, easy to understand and self-describing. It is used as an alternative to XML. JSON is very popular nowadays. JSON represents objects in structured text format and data stored in key-value pairs.

How can I convert JSON to string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);


1 Answers

just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]";  

You'd need to create a C# class called, for example, Person defined as so:

public class Person {  public int Age {get;set;}  public string Name {get;set;} } 

You can now deserialize the JSON string into an array of Person by doing:

JavaScriptSerializer js = new JavaScriptSerializer(); Person [] persons =  js.Deserialize<Person[]>(json); 

Here's a link to JavaScriptSerializer documentation.

Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.

like image 179
Icarus Avatar answered Sep 30 '22 02:09

Icarus