Serializing a list to JSON - c#

I have an object model that looks like this:
public MyObjectInJson
{
public long ObjectID {get;set;}
public string ObjectInJson {get;set;}
}
The property ObjectInJson is an already serialized version an object that contains nested lists. For the moment, I'm serializing the list of MyObjectInJson manually like this:
StringBuilder TheListBuilder = new StringBuilder();
TheListBuilder.Append("[");
int TheCounter = 0;
foreach (MyObjectInJson TheObject in TheList)
{
TheCounter++;
TheListBuilder.Append(TheObject.ObjectInJson);
if (TheCounter != TheList.Count())
{
TheListBuilder.Append(",");
}
}
TheListBuilder.Append("]");
return TheListBuilder.ToString();
I wonder if I can replace this sort of dangerous code with JavascriptSerializer and get the same results.
How would I do this?

If using .Net Core 3.0 or later;
Default to using the built in System.Text.Json parser implementation.
e.g.
using System.Text.Json;
var json = JsonSerializer.Serialize(aList);
alternatively, other, less mainstream options are available like Utf8Json parser and Jil: These may offer superior performance, if you really need it but, you will need to install their respective packages.
If stuck using .Net Core 2.2 or earlier;
Default to using Newtonsoft JSON.Net as your first choice JSON Parser.
e.g.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(aList);
you may need to install the package first.
PM> Install-Package Newtonsoft.Json
For more details see and upvote the answer that is the source of this information.
For reference only, this was the original answer, many years ago;
// you need to reference System.Web.Extensions
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);

You can also use Json.NET. Just download it at http://james.newtonking.com/pages/json-net.aspx, extract the compressed file and add it as a reference.
Then just serialize the list (or whatever object you want) with the following:
using Newtonsoft.Json;
string json = JsonConvert.SerializeObject(listTop10);
Update: you can also add it to your project via the NuGet Package Manager (Tools --> NuGet Package Manager --> Package Manager Console):
PM> Install-Package Newtonsoft.Json
Documentation: Serializing Collections

There are two common ways of doing that with built-in JSON serializers:
JavaScriptSerializer
var serializer = new JavaScriptSerializer();
return serializer.Serialize(TheList);
DataContractJsonSerializer
var serializer = new DataContractJsonSerializer(TheList.GetType());
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, TheList);
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd();
}
}
Note, that this option requires definition of a data contract for your class:
[DataContract]
public class MyObjectInJson
{
[DataMember]
public long ObjectID {get;set;}
[DataMember]
public string ObjectInJson {get;set;}
}

public static string JSONSerialize<T>(T obj)
{
string retVal = String.Empty;
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(ms, obj);
var byteArray = ms.ToArray();
retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
}
return retVal;
}

.NET already supports basic Json serialization through the System.Runtime.Serialization.Json namespace and the DataContractJsonSerializer class since version 3.5. As the name implies, DataContractJsonSerializer takes into account any data annotations you add to your objects to create the final Json output.
That can be handy if you already have annotated data classes that you want to serialize Json to a stream, as described in How To: Serialize and Deserialize JSON Data. There are limitations but it's good enough and fast enough if you have basic needs and don't want to add Yet Another Library to your project.
The following code serializea a list to the console output stream. As you see it is a bit more verbose than Json.NET and not type-safe (ie no generics)
var list = new List<string> {"a", "b", "c", "d"};
using(var output = Console.OpenStandardOutput())
{
var writer = new DataContractJsonSerializer(typeof (List<string>));
writer.WriteObject(output,list);
}
On the other hand, Json.NET provides much better control over how you generate Json. This will come in VERY handy when you have to map javascript-friendly names names to .NET classes, format dates to json etc.
Another option is ServiceStack.Text, part of the ServicStack ... stack, which provides a set of very fast serializers for Json, JSV and CSV.

building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x
using Newtonsoft.Json;
static class JsonObj
{
/// <summary>
/// Deserializes a json file into an object list
/// Author: Joseph Poirier 2/26/2019
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public static List<T> DeSerializeObject<T>(string fileName)
{
List<T> objectOut = new List<T>();
if (string.IsNullOrEmpty(fileName)) { return objectOut; }
try
{
// reading in full file as text
string ss = File.ReadAllText(fileName);
// went with <dynamic> over <T> or <List<T>> to avoid error..
// unexpected character at line 1 column 2
var output = JsonConvert.DeserializeObject<dynamic>(ss);
foreach (var Record in output)
{
foreach (T data in Record)
{
objectOut.Add(data);
}
}
}
catch (Exception ex)
{
//Log exception here
Console.Write(ex.Message);
}
return objectOut;
}
}
call to process
{
string fname = "../../Names.json"; // <- your json file path
// for alternate types replace string with custom class below
List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}
or this call to process
{
string fname = "../../Names.json"; // <- your json file path
// for alternate types replace string with custom class below
List<string> jsonFile = new List<string>();
jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}

If you're doing this in the context of a asp.Net Core API action, the conversion to Json is done implicitly.
[HttpGet]
public ActionResult Get()
{
return Ok(TheList);
}

using System;
using System.Text.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<ErrorDetail> aList = new List<ErrorDetail>();
ErrorDetail a = new ErrorDetail{ ColumnName="aaa", ErrorText="abbbb"};
ErrorDetail c = new ErrorDetail{ ColumnName="ccc", ErrorText="cccc"};
ErrorDetail b = new ErrorDetail{ ColumnName="ccc", ErrorText="cccc"};
aList.Add(a);
aList.Add(b);
aList.Add(c);
var json = JsonSerializer.Serialize(aList);
Console.WriteLine(json);
}
public class ErrorDetail
{
public string ColumnName { get; set; }
public string ErrorText { get; set; }
}
}

I tried the other answers here to serialize parameters for a POST request, but my backend did not like the fact that I was sending up a string version of my array. I did not want to have to always check if the type of a parameter is a string and convert it to an array.
I'm using Json.NET (which is now built into C#), and I convert my List to an array and let the converter handle the rest.
public class MyObjectInJson
{
public long ID;
public OtherObject[] array;
}
You can convert your List into an array using list.ToArray();
And then finally using the JsonConvert, you can turn the entire object into a string:
string jsonString = JsonConvert.SerializeObject(objectInJson);
Hope this helps someone else.

Related

Serialize & Deserialize C# user Defined Classes in .Net

I m working with Core Web API and I have the challenge to nest different class objects into an ArrayList and send them over the FromBody object, the issue is I have to pack them in a way that on the receiving side I deserialize them into their respective objects.
an example is below.
[Serializable]
public class M1
{
public string Name { get; set; }
public int Age { get; set; }
}
[Serializable]
public class M2 : M1
{
public string Gender { get; set; }
public int Height { get; set; }
}
static void Main(string[] args)
{
try
{
M1 mObj = new M1();
M2 m2Obj = new M2();
ArrayList alist = new ArrayList();
mObj.Name = "Apple";
mObj.Age = 20;
m2Obj.Name = "Banana";
m2Obj.Age = 30;
m2Obj.Gender = "Male";
m2Obj.Height = 6;
alist.Add(mObj);
alist.Add(m2Obj);
string result = string.Empty;
M1 mObjD = new M1();
M2 mObj2D = new M2();
//Method1
try
{
result = Newtonsoft.Json.JsonConvert.SerializeObject(alist, Formatting.Indented);
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(result);
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//Method 2
try
{
result = Newtonsoft.Json.JsonConvert.SerializeObject(mObj, Formatting.Indented);
result = result + Newtonsoft.Json.JsonConvert.SerializeObject(m2Obj, Formatting.Indented);
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(result);
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
For the first method its throwing error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SerliazeDeserliaze.M1' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array of a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
for the second method, it says
Additional text encountered after finished reading JSON content: {. Path '', line 4, position 2.
By doing some hack I have done that different way.
M1 mObj = new M1();
M2 m2Obj = new M2();
ArrayList alist = new ArrayList();
ArrayList alistb = new ArrayList();
mObj.Name = "Apple";
mObj.Age = 20;
m2Obj.Name = "Banana";
m2Obj.Age = 30;
m2Obj.Gender = "Male";
m2Obj.Height = 6;
alist.Add(mObj);
alist.Add(m2Obj);
string result = string.Empty;
M1 mObjD = new M1();
M2 mObj2D = new M2();
string json = JsonConvert.SerializeObject(alist, Formatting.Indented, new KeysJsonConverter(typeof(ArrayList)));
alistb= JsonConvert.DeserializeObject<ArrayList>(json, new KeysJsonConverter(typeof(ArrayList)));
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(alistb[0].ToString());
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(alistb[1].ToString());
Serializing the list into JSON and then Deserializing it in a reverse way get the job done.
If you serialize list of object, you should deserialize it also into list:
string result = Newtonsoft.Json.JsonConvert.SerializeObject(aList, Formatting.Indented);
List<M1> mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<List<M1>>(result);
JSON supports the following two data structures,
Collection of name/value pairs - This Data Structure is supported by different programming languages.
Ordered list of values - It includes an array, list, vector or sequence, etc.
JSON has the following styles,
Object
An unordered "name/value" assembly. An object begins with "{" and ends with "}". Behind each "name", there is a colon. And comma is used to separate much "name/value". For example,
var user = {"name":"Manas","gender":"Male","birthday":"1987-8-8"}
Array
Value order set. An array begins with "[" and end with "]". And values are separated with commas. For example,
var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}},
{"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]
String
Any quantity Unicode character assembly which is enclosed with quotation marks. It uses backslash to escape.
var userlist = "{\"ID\":1,\"Name\":\"Manas\",\"Address\":\"India\"}"
We can implement JSON Serialization/Deserialization in the following three ways:
Using JavaScriptSerializer class
Using DataContractJsonSerializer class
Using JSON.NET library
Using DataContractJsonSerializer
DataContractJsonSerializer class helps to serialize and deserialize JSON.
It is present in namespace System.Runtime.Serialization.Json which is
available in assembly System.Runtime.Serialization.dll. Using the
class we can serialize an object into JSON data and deserialize JSON
data into an object.
Let's say there is Employee class with properties such as name, address, and property values also assigned. Now we can convert the Employee class instance to the JSON document. This JSON document can be deserialized into the Employee class or another class with an equivalent data contract. The following code snippets demonstrate about serialization and deserialization.
Let's create a custom class BlogSite for serialization and deserialization,
[DataContract]
class BlogSite
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
}
C# Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and create an instance of MemoryStream class to write object(BlogSite). Lastly it creates an instance of StreamReader class to read JSON data from MemorySteam object.
BlogSite bsObj = new BlogSite()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(BlogSite));
MemoryStream msObj = new MemoryStream();
js.WriteObject(msObj, bsObj);
msObj.Position = 0;
StreamReader sr = new StreamReader(msObj);
// "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}"
string json = sr.ReadToEnd();
sr.Close();
msObj.Close();
C# Deserialization
In Deserialization, it does the opposite of Serialization, which means it converts JSON string to a custom .Net object. In the following code, it creates an instance of BlogSite class and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and creating an instance of MemoryStream class to write an object(BlogSite). Lastly, it creates an instance of StreamReader class to read JSON data from MemorySteam object.
string json = "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}";
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
// Deserialization from JSON
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite));
BlogSite bsObj2 = (BlogSite)deserializer.ReadObject(ms);
Response.Write("Name: " + bsObj2.Name); // Name: C-sharpcorner
Response.Write("Description: " + bsObj2.Description); // Description: Share Knowledge
}
C# Using JavaScriptJsonSerializer
JavaScriptSerializer is a class that helps to serialize and deserialize JSON. It is present in the namespace System.Web.Script.Serialization is available in assembly System.Web.Extensions.dll. To serialize a .Net object to JSON string use the Serialize method. It's possible to deserialize JSON string to .Net object using Deserialize or DeserializeObject methods. Let's see how to implement serialization and deserialization using JavaScriptSerializer.
Following code, a snippet is to declare a custom class of BlogSites type.
class BlogSites
{
public string Name { get; set; }
public string Description { get; set; }
}
C# Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then we create an instance of JavaScriptSerializer and call Serialize() method by passing object(BlogSites). It returns JSON data in string format.
// Creating BlogSites object
BlogSites bsObj = new BlogSites()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
// Serializing object to json data
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonData = js.Serialize(bsObj); // {"Name":"C-sharpcorner","Description":"Share Knowledge"}
C# Deserialization
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.
// Deserializing json data to object
JavaScriptSerializer js = new JavaScriptSerializer();
BlogSites blogObject = js.Deserialize<BlogSites>(jsonData);
string name = blogObject.Name;
string description = blogObject.Description;
// Other way to whithout help of BlogSites class
dynamic blogObject = js.Deserialize<dynamic>(jsonData);
string name = blogObject["Name"];
string description = blogObject["Description"];
C# Using Json.NET
Json.NET is a third-party library that helps conversion between JSON text and .NET object using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent text and back again by mapping the .NET object property names to the JSON property names. It is open-source software and free for commercial purposes.
The following are some awesome features,
Flexible JSON serializer for converting between .NET objects and JSON.
LINQ to JSON for manually reading and writing JSON.
High performance, faster than .NET's built-in JSON serializers.
Easy to read JSON.
Convert JSON to and from XML.
Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone.
Let’s start learning how to install and implement:
In Visual Studio, go to Tools Menu -> Choose Library Package Manager -> Package Manager Console. It opens a command window where we need to put the following command to install Newtonsoft.Json.
Install-Package Newtonsoft.Json
OR
In Visual Studio, Tools menu -> Manage Nuget Package Manager Solution and type “JSON.NET” to search it online. Here's the figure,
Json.NET
Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then it calls static method SerializeObject() of JsonConvert class by passing object(BlogSites). It returns JSON data in string format.
// Creating BlogSites object
BlogSites bsObj = new BlogSites()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
// Convert BlogSites object to JOSN string format
string jsonData = JsonConvert.SerializeObject(bsObj);
Response.Write(jsonData);
C# Deserialization
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
string json = #"{
'Name': 'C-sharpcorner',
'Description': 'Share Knowledge'
}";
BlogSites bsObj = JsonConvert.DeserializeObject<BlogSites>(json);
Response.Write(bsObj.Name);
JSON.NET, visit here.
In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. Here's the

Binary serialization without serializable attribute

I want to serailize my object and used BinaryFormatter class.
public static byte[] BinarySerialize(IMessage message)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, message);
return stream.ToArray();
}
}
But when I run the code, throws an exception.
SerializationException: Object is not marked as serializable.
I think this exception thrown by BinaryFormatter.
I do not want to mark as [Serializable] my objects. Or my library users may forget mark as [Serializable] their own Messages.
Is there any other way to binary serialize my objects without using [Serializable] attribute?
Since [Serializable] attribute cannot be added runtime, there are nooptions if you want to stick to the .Net built in Serialization.
You can
Use ISerializable interface in IMessage so that users has to implement Serialization in their implementations
Use an external library such as: http://sharpserializer.codeplex.com/ And by the way, they have moved to GitHub. See: https://github.com/polenter/SharpSerializer
public static byte[] BinarySerialize(IMessage message)
{
using (var stream = new MemoryStream())
{
var serializer = new SharpSerializer(true);
serializer.Serialize(message, stream );
return stream.ToArray();
}
}
Use JSON serialization
In addition to the other answers regarding 3rd party libs, depending on your needs you may choose to use XmlSerializer. (Better yet use a JSON serializer that doesn't require the SerializeableAttribute.)
These serializers do not require [Serializeable]. However, the XmlSerializer doesn't allow serialization of interfaces either. If you are good with concrete types it works. Compare serialization options.
E.G.
void Main()
{
var serialized = Test.BinarySerialize(new SomeImpl(11,"Hello Wurld"));
}
public class Test
{
public static string BinarySerialize(SomeImpl message)
{
using (var stream = new StringWriter())
{
var formatter = new XmlSerializer(typeof(SomeImpl));
formatter.Serialize(stream, message);
return stream.ToString().Dump();
}
}
}
public class SomeImpl
{
public int MyProperty { get;set;}
public string MyString { get;set; }
public SomeImpl() {}
public SomeImpl(int myProperty, String myString)
{
MyProperty = myProperty;
MyString = myString;
}
}
To avoid Net4x built in Serialization that require the [Serializable] attribute, use Newtonsoft.Json or System.Text.Json in netcore 3.1+ or Net5
string json= JsonConvert.SerializeObject(message);
//or System.Text.Json in netcore 3.1+
string json= System.Text.Json. JsonSerializer.Serialize(message);

How to parse non-array JSON?

I am trying to read json from a local .json file and parse the contents using StreamReader and Json.NET. Json & my code:
contents of .json file: {"rate":50,"information":{"height":70,"ssn":43,"name":"andrew"}}
using (var sr = new StreamReader(pathToJsonFile))
{
dynamic jsonArray = JsonConvert.DeserializeObject(sr.ReadToEnd());
foreach(var item in jsonArray)
{
Console.WriteLine(item.rate);
Console.WriteLine(item.ssn);
}
}
This gives me an error on the line foreach(var item in array): Object reference not set to an instance of an object. I am guessing this is because my json is not actually an array but that is how I am trying to parse it. How can I parse this json in order to pull out fields such as rate or ssn?
NB - please do not flag this question as a duplicate of Read and parse a Json File in C#, as that is where I got my original code from.
EDIT: As has been pointed out in other answers, jsonArray is null. That explains my error but still does not answer my question. How else can I parse this json in order to extract the desired fields?
A couple things:
If you want to manually parse out the values, you should try using JObject rather than JsonConvert.DeserializeObject. The following code should work:
dynamic jsonObject = JObject.Parse("{'rate':50,'information':{'height':70,'ssn':43,'name':'andrew'}}");
Console.WriteLine(jsonObject["rate"]);
Console.WriteLine(jsonObject["information"]["ssn"]);
However, if you know how the json is structured, you should create a .net class like:
public class Person
{
public int rate {get;set;}
public Information information {get;set;}
}
public class Information
{
public int height {get;set;}
public int ssn {get;set;}
public string name {get;set;}
}
and then use:
var person = JsonConvert.DeserializeObject<Person>(thestringtodeserialize);
That way you can have a strongly typed object.
In any case, I would check for null (DeserializeObject can obviously return null):
using (var sr = new StreamReader(pathToJsonFile))
{
dynamic jsonArray = JsonConvert.DeserializeObject(sr.ReadToEnd());
if(jsonArray != null) //new check here
{
foreach(var item in jsonArray)
{
Console.WriteLine(item.rate);
Console.WriteLine(item.ssn);
}
}
I am guessing this is because my json is not actually an array
True, the returned object is dynamic, so make use of dynamic:
var json = "{\"rate\":50,\"information\":{\"height\":70,\"ssn\":43,\"name\":\"andrew\"}}";
dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine("rate: {0}. ssn: {1}", obj.rate, obj.information.ssn);
See live sample here: https://dotnetfiddle.net/nQYuyX
Are you sure it's an array?
If that's the format the you expect from Json, maybe you should consider defining a class.
For example:
class SomeJsonObject
{
public int rate {get;set;}
[JsonProperty("information")] //if you want to name your property something else
public InformationObject Information {get;set;}
}
class InformationObject
{
[JsonProperty("height", NullValueHandling = NullValueHandling.Ignore)] //some other things you can do with Json
public int Height {get;set;}
public int ssn {get;set;}
public string name {get;set;}
}
This way you can just deserialize it to an object:
SomeJsonObject jsonArray = JsonConvert.DeserializeObject<SomeJsonObject>(sr.ReadToEnd());
I think your question is similar to this Deserialize JSON with C# . you can use JavaScriptSerializer
I don't get a null reference (with Json.net 6.0.3) but your code has one obvious bug:
static void Main(string[] args)
{
string s = "{'rate':50,'information':{'height':70,'ssn':43,'name':'andrew'}}".Replace('\'', '\"');
var obj = JsonConvert.DeserializeObject(s);
dynamic jsonArray = obj;
foreach (var item in jsonArray)
{
Console.WriteLine(item.rate);
Console.WriteLine(item.ssn);
}
}
The bug is Console.WriteLine(item.rate) will throw.
Your 'array' jsonArray is not actually an array, it is a dictionary!
Therefore, item=the first Key-Value-pair in the dictionary, = {"rate":50}.
You can prevent the code from throwing by getting rid of your foreach loop.
i would fire up nuget and get the JSON.net package
https://www.nuget.org/packages/Newtonsoft.Json/
http://james.newtonking.com/json
it is well documented and can save you a tonne of work.
see also http://json2csharp.com/
EDIT: you are already using this

Create Self Constructing Objects with JavaScriptSerializer (JSON.PARSE equivalent)

I'm creating a flexible framework for creating and storing settings for third party developers.
One of the better choices we made was to create a system where the developers created their own settings with JSON, and simply serialized the objects later.
I.E.
public class YammerConfig
{
public string yammerClientId { get; set; }
public string yammerNetwork { get; set; }
public YammerConfig(string js)
{
var ser = new JavaScriptSerializer();
var sam = ser.Deserialize<YammerConfig>(js);
yammerClientId = sam.yammerClientId;
yammerNetwork = sam.yammerNetwork;
}
}
This has been an effective way to store settings in a database without having to reconfigure new tables for unique sets of information.
I would love to take this one step further, the way JavaScript itself does, and create objects on the fly that don't need to be manually serialized.
Is it possible to create the equivalent of json.parse in .NET C#?
Why you don't use extention method
For example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace Stackoverflow.Helpers
{
public static class JsonHelper
{
private static JavaScriptSerializer ser = new JavaScriptSerializer();
public static T ToJSON<T>(this string js) where T : class
{
return ser.Deserialize<T>(js);
}
public static string JsonToString(this object obj)
{
return ser.Serialize(obj);
}
}
}
easy to use
//Deserialize
string s = "{yammerClientId = \"1\",yammerNetwork = \"2\"}";
YammerConfig data = s.ToJSON<YammerConfig>();
//Serialize
string de = data.JsonToString();
Can you use Newtonsoft.Json (home) to do the deserializing quite simply. It's just one line, and works way better than the built in one.
var settings = JsonConvert.DeerializeObject<YammerSettings>(json);
var json = JsonConvert.SerializeObject(yammerSettingsObject);
// you can also serialized and deserialize anon objects, control formatting,
// do dictinaries and lists directly, datasets, and on and on
Check out this website for more Examples
If this doesn't cover what you are looking for, can you be more specific? This is the only JSON library we use anymore, and it takes care of everything.

Add binding to json using JavaScriptSerializer with list asp.net c#

I use to build my json return string by hand using vbscript and would add a binding, and then in javascript i could say something simple like
data.response[0].key
which would look like this in json
{"response":[{"key":"value"},{"key":"value"}] }
I just starting working with jquery ajax to asp.net in c# and i found the only way to make valid json in c# is to use the JavaScriptSerializer. This is fine, except im not sure how to get that type of binding when serializing my list. I only have one item in my json for testing
d=[{"h":"hi"}] //This is what shows in fiddler
i want it too look similar to the above
d={"response":[{"h":"hi"}] }
Im not sure how to create this type of json response object using c#, though i am sure it is possible. Here is the code for my test serialization.
private static string Serialize(object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string SomeMethod()
{
List<Samp> samp = new List<Samp>()
{
new Samp{h = "hi"}
};
return Serialize(samp);
}
/
public class Samp
{
public string h = "";
}
return Serialize( new { response = samp });

Categories