public class ExamplePerson
{
public String Name { get; set; }
public Int32 Age { get; set; }
public override String ToString()
{
return String.Format("Name: {0}, Age: {1}", Name, Age);
}
}
public class ExamplePhone
{
public enum PhoneType { Home = 0, Mobile }
public PhoneType Type { get; set; }
public String Number { get; set; }
public override String ToString()
{
return String.Format("Type: {0}, Number: {1}", Type, Number);
}
}
public class ExamplePhoneList : List<ExamplePhone> { }
public class ExamplePerson2
{
public String Name { get; set; }
public Int32 Age { get; set; }
public ExamplePhone[] Phone { get; set; }
public ExamplePhoneList PhoneList { get; set; }
public override String ToString()
{
return String.Format("Name: {0}, Age: {1}", Name, Age);
}
}
static void Main(string[] args)
{
// Welcome to this tutorial!
// I will assume that you are familiar with JSON data format. Here is an example:
// { "key1": 1, "key2": "two" }, or more complicated:
// { "key1": "value1", "key2": 123, "key3": [ 1, 2, "3", { "key1": true } ], key4: { "key1": 1 } }
// As you know, there are two JSON data objects, JSON Object and JSON Array.
// JSON Object is set of key/value pairs, where keys are Strings.
// JSON Array is array which holds only values in strict order, accessing them by index.
// Value can be any of String, Number, Boolean, JSON Object or JSON Array.
// In this library you will find both JSONObject and JSONArray data type, so that you
// can easily manipulate JSON, create it, convert it into String and from String back
// into object, and accessing its data, like with any other native type in C#.
// But what is much unique in this library is that even value has its own type, named
// JSONValue, and any type, primitive or complex, can also be represented as this type.
// But let's move to the examples.
// Creating JSONObject
Debug.WriteLine("\r\nCreating JSONObject");
JSONObject jsonObject = new JSONObject();
// this will create new key if it does not exists, otherwise it will create a new one.
jsonObject["key1"] = "value1";
jsonObject["key2"] = true;
jsonObject["key3"] = 5;
Debug.WriteLine(jsonObject); // it will be automatically converted to String before output.
jsonObject.Remove("key3");
Debug.WriteLine(jsonObject);
String jsonString = jsonObject; // this will also create String from JSONObject.
Debug.WriteLine(jsonObject);
// More about creating JSONObject
Debug.WriteLine("\r\nMore about creating JSONObject");
jsonObject = new JSONObject(new object[,] {
{ "key1", "1" }, { "key2", 2 }});
Debug.WriteLine(jsonObject);
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("key1", "value1"); dictionary.Add("key2", DateTime.Now);
jsonObject = new JSONObject(dictionary);
jsonObject.Add("key3", 3);
Debug.WriteLine(jsonObject);
// Accessing JSONObject values
Debug.WriteLine("\r\nAccessing JSONObject values");
jsonObject = new JSONObject(new object[,] {
{ "key1", "1" },
{ "key2", -2.5 },
{ "key3", new JSONObject(new object[,] {
{ "key1", true }, { "key2", 5 }}) } });
Decimal value1 = jsonObject["key2"];
Debug.WriteLine(value1);
UInt32 value2 = jsonObject["key3"]["key2"];
Debug.WriteLine(value2);
jsonObject["key3"]["key1"] = false;
Debug.WriteLine(jsonObject["key3"]["key1"]);
// Parsing JSON Object string
Debug.WriteLine("\r\nParsing JSON Object string");
jsonObject = JSONObject.Parse("{\"key1\":1,\"key2\":{\"key1\":true,\"key2\":\"2.5\"}}");
Debug.WriteLine(jsonObject);
// Creating JSONArray
Debug.WriteLine("\r\nCreating JSONArray");
JSONArray jsonArray = new JSONArray();
jsonArray.Add("value1"); jsonArray.Add(2); jsonArray.Add(true);
Debug.WriteLine(jsonArray);
jsonArray.RemoveAt(1);
jsonArray.Insert("value0", 0);
Debug.WriteLine(jsonArray);
// More about creating JSONArray
Debug.WriteLine("\r\nMore about creating JSONArray");
jsonArray = new JSONArray(new object[] { true, "value2" });
Debug.WriteLine(jsonArray);
List<object> list = new List<object>();
list.Add(1); list.Add("value2");
list.Add(new JSONObject(new Object[,] {
{ "key1", "value1"}, { "key2", true }}));
jsonArray = new JSONArray(list);
Debug.WriteLine(jsonArray);
// Accessing JSONArray values
Debug.WriteLine("\r\nAccessing JSONArray values");
jsonArray = new JSONArray(new object[] {
true, "value2",
new JSONObject(new object[,] { { "key1", "value1" }, { "key2", 2 } })
});
String value3 = jsonArray[1];
Debug.WriteLine(value3);
String value4 = jsonArray[2]["key2"];
Debug.WriteLine(value4);
// Parsing JSON Array string
Debug.WriteLine("\r\nParsing JSON Array string");
jsonArray = JSONArray.Parse("[1,{\"key1\":true,\"key2\":\"2.5\"}]");
Debug.WriteLine(jsonArray);
// You have noticed that I'm using nested structures in this example. Parsers
// can also parse nested objects and create complex nested native objects,
// so that JSONObject can parse nested JSON Array and JSONArray can parse
// nested JSON Object.
// But this two types are even more related because there is a type which
// encapsulates them (not really encapsulate in C# term, it's just a wrapper)
// so that it gives them common properties, and that is JSONValue. So every
// value in that nested structure is, in fact, an object of this type.
// JSONValue examples
Debug.WriteLine("\r\nJSONValue examples");
JSONValue jsonValue = new JSONObject();
jsonValue["key1"] = "value1";
Debug.WriteLine(jsonValue);
jsonValue = JSONValue.Parse("[1,{\"key1\":true,\"key2\":2.5}]");
Debug.WriteLine(jsonValue);
JSONValue jsonValue2 = jsonValue[1]["key1"];
Boolean value5 = jsonValue2;
Debug.WriteLine(value5);
// And of course, Null value example
Debug.WriteLine("\r\nNull value example");
jsonValue = JSONValue.Parse("[1,{\"key1\":null,\"key2\":\"2.5\"}]");
Debug.WriteLine(jsonValue[1]["key1"].ToString());
// More nested example
Debug.WriteLine("\r\nMore nested example");
String a = "{\"key1\":\"value1\",\"key2\":{\"key21\":{\"key211\":\"value211\"},\"key22\":{\"key221\":\"value221\"}},\"key3\":{\"key31\":\"value31\"}}";
JSONObject b = JSONObject.Parse(a);
Debug.WriteLine(b.ToString());
// Example with whitespaces (now supported)
Debug.WriteLine("\r\nExample with whitespaces");
jsonValue = JSONValue.Parse(" {\"key1\" : {\"key1\" : \"value1\", \"key2\":\"value2\"} , \"key2\":[1 ,\"2.5\" ]}");
Debug.WriteLine(jsonValue.ToString());
// Parsing invalid string
Debug.WriteLine("\r\nParsing invalid string");
jsonValue = JSONValue.Parse("");
Debug.WriteLine(String.Format("jsonValue = {0}", jsonValue == null ? "null" : jsonValue.ToString()));
// Converting JSONValue to List<JSONValue> and Dictionary<String, JSONValue>
Debug.WriteLine("\r\nConverting JSONValue to List<JSONValue> and Dictionary<String, JSONValue>");
jsonValue = JSONArray.Parse("[1,{\"key1\":true,\"key2\":\"2.5\"}]");
List<JSONValue> list2 = (List<JSONValue>)jsonValue;
Debug.WriteLine(list2.ToString());
jsonValue = (JSONValue)list2;
Debug.WriteLine(jsonValue.ToString());
jsonValue = JSONValue.Parse("{\"key1\":1,\"key2\":{\"key1\":true,\"key2\":\"2.5\"}}");
Dictionary<String, JSONValue> dictionary2 = (Dictionary<String, JSONValue>)jsonValue;
Debug.WriteLine(dictionary2.ToString());
jsonValue = (JSONValue)dictionary2;
Debug.WriteLine(jsonValue.ToString());
// Serialization of a class instance
Debug.WriteLine("\r\nSerialization of a class instance");
jsonValue = JSONValue.Serialize(new ExamplePerson() { Name = "John", Age = 31 });
Debug.WriteLine(jsonValue.ToString());
ExamplePerson person = jsonValue.Deserialize<ExamplePerson>();
Debug.WriteLine(person);
// Serialization of a Dictionary<String, Object> instance
Debug.WriteLine("\r\nSerialization of a Dictionary<String, Object> instance");
jsonObject = JSONObject.Serialize(new Dictionary<String, Object>() {
{ "Name", "John" }, { "Age", 31 } });
Debug.WriteLine(jsonObject.ToString());
dictionary = jsonObject.Deserialize<Dictionary<String, Object>>();
Debug.WriteLine(String.Format("Name: {0}, Age: {1}", dictionary["Name"], dictionary["Age"]));
// Serialization of a Dictionary<String, JSONValue> instance
Debug.WriteLine("\r\nSerialization of a Dictionary<String, JSONValue> instance");
jsonObject = JSONObject.Serialize(new Dictionary<String, JSONValue>() {
{ "Name", new JSONObject() { { "First", "John" }, { "Last", "Lennon" } } },
{ "Age", 31 }, { "BirthDate", new DateTime(1940, 10, 9) } });
Debug.WriteLine(jsonObject.ToString());
dictionary2 = jsonObject.Deserialize<Dictionary<String, JSONValue>>();
Debug.WriteLine(String.Format("Name: < First: {0}, Last: {1} >, Age: {2}, BirthDate: {3}",
dictionary2["Name"]["First"], dictionary2["Name"]["Last"], dictionary2["Age"],
dictionary2["BirthDate"]));
// Serialization of a List<JSONValue> instance
Debug.WriteLine("\r\nSerialization of a List<JSONValue> instance");
List<JSONValue> listJSONValue = new List<JSONValue>() { new JSONValue(1), new JSONValue("dva") };
jsonArray = JSONArray.Serialize(listJSONValue);
Debug.WriteLine(jsonArray.ToString());
listJSONValue = jsonArray.Deserialize<List<JSONValue>>();
Debug.WriteLine(String.Format("[ {0}, {1} ]", listJSONValue[0].Value, listJSONValue[1].Value));
// Serialization of a List<Object> instance
Debug.WriteLine("\r\nSerialization of a List<Object> instance");
List<Object> listObject = new List<Object>() { 1, "dva" };
jsonArray = JSONArray.Serialize(listObject);
Debug.WriteLine(jsonArray.ToString());
listObject = jsonArray.Deserialize<List<Object>>();
Debug.WriteLine(String.Format("[ {0}, {1} ]", listObject[0], listObject[1]));
// Serialization of an array
Debug.WriteLine("\r\nSerialization of an array");
int[] array = new int[] { 1, 2 };
jsonArray = JSONArray.Serialize(array);
Debug.WriteLine(jsonArray.ToString());
array = jsonArray.Deserialize<int[]>();
Debug.WriteLine(jsonArray);
// Serialization of a complex object
Debug.WriteLine("\r\nSerialization of a complex object");
jsonValue = JSONValue.Serialize(new ExamplePerson2() {
Name = "John",
Age = 31,
Phone = new ExamplePhone[] {
new ExamplePhone() { Type = ExamplePhone.PhoneType.Home, Number = "111" },
new ExamplePhone() { Type = ExamplePhone.PhoneType.Mobile, Number = "222" }},
PhoneList = new ExamplePhoneList {
new ExamplePhone() { Type = ExamplePhone.PhoneType.Home, Number = "111" },
new ExamplePhone() { Type = ExamplePhone.PhoneType.Mobile, Number = "222" }}});
jsonValue["Phone"][0]["Type"].TreatEnumAsInt = true;
Debug.WriteLine(jsonValue.ToString());
ExamplePerson2 person2 = jsonValue.Deserialize<ExamplePerson2>();
Debug.WriteLine(JSONValue.Serialize(person2).ToString());
// Be careful when parsing invalid strings, or when (implicitly or explicitly)
// typecast values, because exception will be thrown on any invalid operation.
// Also notice the difference between String typecast and ToString() method.
// Typecast will simply convert object to String. ToString() methods makes
// string representation of JSON value, so that String value <value1> becomes
// <"value1">, as it would be in JSON representation. Also, <null> value becomes
// <null> string in JSON. Use ToString() method to display JSON string,
// and typecast to convert values.
// I hope that you like this approach of making JSON for .NET simple and usable.
// And that you enjoyed reading this tutorial, too.
Console.ReadKey(false); return;
}