Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting list to json format - quick and easy way

Tags:

c#

asp.net

Let's say I have an object MyObject that looks like this:

public class MyObject {   int ObjectID {get;set;}   string ObjectString {get;set;} }  

I have a list of MyObject and I'm looking to convert it in a json string with a stringbuilder. I know how to create a JavascriptConverter and create a json string by passing a list and having the converter build the string but in this particular case I'm looking to avoid the overhead and go straight to a json string with a foreach loop on the list like this:

StringBuilder JsonString = new StringBuilder();  foreach(MyObject TheObject in ListOfMyObject) {  } 

I've tried to use this method by appending with commas and quotes but it hasn't worked out (yet).

Thanks for your suggestions.

like image 762
frenchie Avatar asked Jun 16 '11 01:06

frenchie


People also ask

How do I convert a list to JSON?

We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.

How do you convert a list to JSON in darts?

We have 3 steps to convert an Object/List to JSON string: create the class. create toJson() method which returns a JSON object that has key/value pairs corresponding to all fields of the class. get JSON string from JSON object/List using jsonEncode() function.

Can JSON just be a list?

JSON is built on two structures:An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

What is converting data to JSON called?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).


2 Answers

I've done something like before using the JavaScript serialization class:

using System.Web.Script.Serialization; 

And:

JavaScriptSerializer jss = new JavaScriptSerializer();  string output = jss.Serialize(ListOfMyObject); Response.Write(output); Response.Flush(); Response.End(); 
like image 108
Mark Ursino Avatar answered Oct 06 '22 20:10

Mark Ursino


3 years of experience later, I've come back to this question and would suggest to write it like this:

string output = new JavaScriptSerializer().Serialize(ListOfMyObject); 

One line of code.

like image 33
frenchie Avatar answered Oct 06 '22 19:10

frenchie