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.
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.
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.
JSON is built on two structures:An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
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).
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With