text
stringlengths
0
13.4k
dynamic jsonObject = new ExpandoObject();
jsonObject.Title = "Merchent of Venice";
jsonObject.Author = "William Shakespeare";
Console.WriteLine(JsonConvert.SerializeObject(jsonObject));
De-serialization
var rawJson = "{\"Name\":\"Fibonacci Sequence\",\"Numbers\":[0, 1, 1, 2, 3, 5, 8, 13]}";
dynamic parsedJson = JObject.Parse(rawJson);
GoalKicker.com – .NET Framework Notes for Professionals
108
Console.WriteLine("Name: " + parsedJson.Name);
Console.WriteLine("Name: " + parsedJson.Numbers.Length);
Notice that the keys in the rawJson object have been turned into member variables in the dynamic object.
This is useful in cases where an application can accept/ produce varying formats of JSON. It is however suggested to
use an extra level of validation for the Json string or to the dynamic object generated as a result of serialization/ de-
serialization.
Section 32.6: Serialization using Json.NET with
JsonSerializerSettings
This serializer has some nice features that the default .net json serializer doesn't have, like Null value handling, you
just need to create the JsonSerializerSettings :
public static string Serialize(T obj)
{
string result = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling
= NullValueHandling.Ignore});
return result;
}
Another serious serializer issue in .net is the self referencing loop. In the case of a student that is enrolled in a
course, its instance has a course property and a course has a collection of students that means a List<Student>
which will create a reference loop. You can handle this with JsonSerializerSettings :
public static string Serialize(T obj)
{
string result = JsonConvert.SerializeObject(obj, new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return result;
}
You can put various serializations option like this:
public static string Serialize(T obj)
{
string result = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling
= NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return result;
}
GoalKicker.com – .NET Framework Notes for Professionals
109
Chapter 33: JSON in .NET with
Newtonsoft.Json
The NuGet package Newtonsoft.Json has become the defacto standard for using and manipulating JSON formatted
text and objects in .NET. It is a robust tool that is fast, and easy to use.
Section 33.1: Deserialize an object from JSON text
var json = "{\"Name\":\"Joe Smith\",\"Age\":21}";
var person = JsonConvert.DeserializeObject<Person>(json);
This yields a Person object with Name "Joe Smith" and Age 21.
Section 33.2: Serialize object into JSON
using Newtonsoft.Json;
var obj = new Person
{
Name = "Joe Smith",
Age = 21
};
var serializedJson = JsonConvert.SerializeObject(obj);
This results in this JSON: {"Name":"Joe Smith","Age":21}
GoalKicker.com – .NET Framework Notes for Professionals
110
Chapter 34: XmlSerializer
Section 34.1: Formatting: Custom DateTime format