-Samples!
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Bson;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Bson
|
||||
{
|
||||
public class DeserializeFromBson
|
||||
{
|
||||
#region Types
|
||||
public class Event
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public DateTime StartDate { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
byte[] data = Convert.FromBase64String("MQAAAAJOYW1lAA8AAABNb3ZpZSBQcmVtaWVyZQAJU3RhcnREYXRlAMDgKWE8AQAAAA==");
|
||||
|
||||
MemoryStream ms = new MemoryStream(data);
|
||||
using (BsonReader reader = new BsonReader(ms))
|
||||
{
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
|
||||
Event e = serializer.Deserialize<Event>(reader);
|
||||
|
||||
Console.WriteLine(e.Name);
|
||||
// Movie Premiere
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Bson;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Bson
|
||||
{
|
||||
public class DeserializeFromBsonCollection
|
||||
{
|
||||
#region Types
|
||||
public class Event
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public DateTime StartDate { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
//IList<Event> e = new List<Event>
|
||||
// {
|
||||
// new Event {StartDate = new DateTime(2013, 3, 31), Name = "Easter"}
|
||||
// };
|
||||
//MemoryStream ms1 = new MemoryStream();
|
||||
//using (BsonWriter writer = new BsonWriter(ms1))
|
||||
//{
|
||||
// JsonSerializer serializer = new JsonSerializer();
|
||||
|
||||
// serializer.Serialize(writer, e);
|
||||
//}
|
||||
|
||||
//string ss = Convert.ToBase64String(ms1.ToArray());
|
||||
//Console.WriteLine(ss);
|
||||
|
||||
#region Usage
|
||||
string s = "MQAAAAMwACkAAAACTmFtZQAHAAAARWFzdGVyAAlTdGFydERhdGUAgDf0uj0BAAAAAA==";
|
||||
byte[] data = Convert.FromBase64String(s);
|
||||
|
||||
MemoryStream ms = new MemoryStream(data);
|
||||
using (BsonReader reader = new BsonReader(ms))
|
||||
{
|
||||
reader.ReadRootValueAsArray = true;
|
||||
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
|
||||
IList<Event> events = serializer.Deserialize<IList<Event>>(reader);
|
||||
|
||||
Console.WriteLine(events.Count);
|
||||
// 1
|
||||
|
||||
Console.WriteLine(events[0].Name);
|
||||
// Easter
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Bson;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Bson
|
||||
{
|
||||
public class SerializeToBson
|
||||
{
|
||||
#region Types
|
||||
public class Event
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public DateTime StartDate { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Event e = new Event
|
||||
{
|
||||
Name = "Movie Premiere",
|
||||
StartDate = new DateTime(2013, 1, 22, 20, 30, 0)
|
||||
};
|
||||
|
||||
MemoryStream ms = new MemoryStream();
|
||||
using (BsonWriter writer = new BsonWriter(ms))
|
||||
{
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
serializer.Serialize(writer, e);
|
||||
}
|
||||
|
||||
string data = Convert.ToBase64String(ms.ToArray());
|
||||
|
||||
Console.WriteLine(data);
|
||||
// MQAAAAJOYW1lAA8AAABNb3ZpZSBQcmVtaWVyZQAJU3RhcnREYXRlAMDgKWE8AQAAAA==
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Json
|
||||
{
|
||||
public class ReadJsonWithJsonTextReader
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'CPU': 'Intel',
|
||||
'PSU': '500W',
|
||||
'Drives': [
|
||||
'DVD read/writer'
|
||||
/*(broken)*/,
|
||||
'500 gigabyte hard drive',
|
||||
'200 gigabype hard drive'
|
||||
]
|
||||
}";
|
||||
|
||||
JsonTextReader reader = new JsonTextReader(new StringReader(json));
|
||||
while (reader.Read())
|
||||
{
|
||||
if (reader.Value != null)
|
||||
Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
|
||||
else
|
||||
Console.WriteLine("Token: {0}", reader.TokenType);
|
||||
}
|
||||
|
||||
// Token: StartObject
|
||||
// Token: PropertyName, Value: CPU
|
||||
// Token: String, Value: Intel
|
||||
// Token: PropertyName, Value: PSU
|
||||
// Token: String, Value: 500W
|
||||
// Token: PropertyName, Value: Drives
|
||||
// Token: StartArray
|
||||
// Token: String, Value: DVD read/writer
|
||||
// Token: Comment, Value: (broken)
|
||||
// Token: String, Value: 500 gigabyte hard drive
|
||||
// Token: String, Value: 200 gigabype hard drive
|
||||
// Token: EndArray
|
||||
// Token: EndObject
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Json
|
||||
{
|
||||
public class WriteJsonWithJsonTextWriter
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
StringBuilder sb = new StringBuilder();
|
||||
StringWriter sw = new StringWriter(sb);
|
||||
|
||||
using (JsonWriter writer = new JsonTextWriter(sw))
|
||||
{
|
||||
writer.Formatting = Formatting.Indented;
|
||||
|
||||
writer.WriteStartObject();
|
||||
writer.WritePropertyName("CPU");
|
||||
writer.WriteValue("Intel");
|
||||
writer.WritePropertyName("PSU");
|
||||
writer.WriteValue("500W");
|
||||
writer.WritePropertyName("Drives");
|
||||
writer.WriteStartArray();
|
||||
writer.WriteValue("DVD read/writer");
|
||||
writer.WriteComment("(broken)");
|
||||
writer.WriteValue("500 gigabyte hard drive");
|
||||
writer.WriteValue("200 gigabype hard drive");
|
||||
writer.WriteEnd();
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
Console.WriteLine(sb.ToString());
|
||||
// {
|
||||
// "CPU": "Intel",
|
||||
// "PSU": "500W",
|
||||
// "Drives": [
|
||||
// "DVD read/writer"
|
||||
// /*(broken)*/,
|
||||
// "500 gigabyte hard drive",
|
||||
// "200 gigabype hard drive"
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class Clone
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o1 = new JObject
|
||||
{
|
||||
{"String", "A string!"},
|
||||
{"Items", new JArray(1, 2)}
|
||||
};
|
||||
|
||||
Console.WriteLine(o1.ToString());
|
||||
// {
|
||||
// "String": "A string!",
|
||||
// "Items": [
|
||||
// 1,
|
||||
// 2
|
||||
// ]
|
||||
// }
|
||||
|
||||
JObject o2 = (JObject) o1.DeepClone();
|
||||
|
||||
Console.WriteLine(o2.ToString());
|
||||
// {
|
||||
// "String": "A string!",
|
||||
// "Items": [
|
||||
// 1,
|
||||
// 2
|
||||
// ]
|
||||
// }
|
||||
|
||||
Console.WriteLine(JToken.DeepEquals(o1, o2));
|
||||
// true
|
||||
|
||||
Console.WriteLine(Object.ReferenceEquals(o1, o2));
|
||||
// false
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class CreateJsonAnonymousObject
|
||||
{
|
||||
#region Types
|
||||
public class Post
|
||||
{
|
||||
public string Title { get; set; }
|
||||
public string Description { get; set; }
|
||||
public string Link { get; set; }
|
||||
public IList<string> Categories { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
List<Post> posts = new List<Post>
|
||||
{
|
||||
new Post
|
||||
{
|
||||
Title = "Episode VII",
|
||||
Description = "Episode VII production",
|
||||
Categories = new List<string>
|
||||
{
|
||||
"episode-vii",
|
||||
"movie"
|
||||
},
|
||||
Link = "episode-vii-production.aspx"
|
||||
}
|
||||
};
|
||||
|
||||
JObject o = JObject.FromObject(new
|
||||
{
|
||||
channel = new
|
||||
{
|
||||
title = "Star Wars",
|
||||
link = "http://www.starwars.com",
|
||||
description = "Star Wars blog.",
|
||||
item =
|
||||
from p in posts
|
||||
orderby p.Title
|
||||
select new
|
||||
{
|
||||
title = p.Title,
|
||||
description = p.Description,
|
||||
link = p.Link,
|
||||
category = p.Categories
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Console.WriteLine(o.ToString());
|
||||
// {
|
||||
// "channel": {
|
||||
// "title": "Star Wars",
|
||||
// "link": "http://www.starwars.com",
|
||||
// "description": "Star Wars blog.",
|
||||
// "item": [
|
||||
// {
|
||||
// "title": "Episode VII",
|
||||
// "description": "Episode VII production",
|
||||
// "link": "episode-vii-production.aspx",
|
||||
// "category": [
|
||||
// "episode-vii",
|
||||
// "movie"
|
||||
// ]
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class CreateJsonCollectionInitializer
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o = new JObject
|
||||
{
|
||||
{"Cpu", "Intel"},
|
||||
{"Memory", 32},
|
||||
{
|
||||
"Drives", new JArray
|
||||
{
|
||||
"DVD",
|
||||
"SSD"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Console.WriteLine(o.ToString());
|
||||
// {
|
||||
// "Cpu": "Intel",
|
||||
// "Memory": 32,
|
||||
// "Drives": [
|
||||
// "DVD",
|
||||
// "SSD"
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class CreateJsonDeclaratively
|
||||
{
|
||||
#region Types
|
||||
public class Post
|
||||
{
|
||||
public string Title { get; set; }
|
||||
public string Description { get; set; }
|
||||
public string Link { get; set; }
|
||||
public IList<string> Categories { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
private List<Post> GetPosts()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
List<Post> posts = GetPosts();
|
||||
|
||||
JObject rss =
|
||||
new JObject(
|
||||
new JProperty("channel",
|
||||
new JObject(
|
||||
new JProperty("title", "James Newton-King"),
|
||||
new JProperty("link", "http://james.newtonking.com"),
|
||||
new JProperty("description", "James Newton-King's blog."),
|
||||
new JProperty("item",
|
||||
new JArray(
|
||||
from p in posts
|
||||
orderby p.Title
|
||||
select new JObject(
|
||||
new JProperty("title", p.Title),
|
||||
new JProperty("description", p.Description),
|
||||
new JProperty("link", p.Link),
|
||||
new JProperty("category",
|
||||
new JArray(
|
||||
from c in p.Categories
|
||||
select new JValue(c)))))))));
|
||||
|
||||
Console.WriteLine(rss.ToString());
|
||||
|
||||
// {
|
||||
// "channel": {
|
||||
// "title": "James Newton-King",
|
||||
// "link": "http://james.newtonking.com",
|
||||
// "description": "James Newton-King's blog.",
|
||||
// "item": [
|
||||
// {
|
||||
// "title": "Json.NET 1.3 + New license + Now on CodePlex",
|
||||
// "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
|
||||
// "link": "http://james.newtonking.com/projects/json-net.aspx",
|
||||
// "category": [
|
||||
// "Json.NET",
|
||||
// "CodePlex"
|
||||
// ]
|
||||
// },
|
||||
// {
|
||||
// "title": "LINQ to JSON beta",
|
||||
// "description": "Annoucing LINQ to JSON",
|
||||
// "link": "http://james.newtonking.com/projects/json-net.aspx",
|
||||
// "category": [
|
||||
// "Json.NET",
|
||||
// "LINQ"
|
||||
// ]
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class CreateJsonDynamic
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
dynamic product = new JObject();
|
||||
product.ProductName = "Elbow Grease";
|
||||
product.Enabled = true;
|
||||
product.Price = 4.90m;
|
||||
product.StockCount = 9000;
|
||||
product.StockValue = 44100;
|
||||
product.Tags = new JArray("Real", "OnSale");
|
||||
|
||||
Console.WriteLine(product.ToString());
|
||||
// {
|
||||
// "ProductName": "Elbow Grease",
|
||||
// "Enabled": true,
|
||||
// "Price": 4.90,
|
||||
// "StockCount": 9000,
|
||||
// "StockValue": 44100,
|
||||
// "Tags": [
|
||||
// "Real",
|
||||
// "OnSale"
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class CreateJsonJTokenWriter
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JTokenWriter writer = new JTokenWriter();
|
||||
writer.WriteStartObject();
|
||||
writer.WritePropertyName("name1");
|
||||
writer.WriteValue("value1");
|
||||
writer.WritePropertyName("name2");
|
||||
writer.WriteStartArray();
|
||||
writer.WriteValue(1);
|
||||
writer.WriteValue(2);
|
||||
writer.WriteEndArray();
|
||||
writer.WriteEndObject();
|
||||
|
||||
JObject o = (JObject)writer.Token;
|
||||
|
||||
Console.WriteLine(o.ToString());
|
||||
// {
|
||||
// "name1": "value1",
|
||||
// "name2": [
|
||||
// 1,
|
||||
// 2
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class CreateJsonManually
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JArray array = new JArray();
|
||||
JValue text = new JValue("Manual text");
|
||||
JValue date = new JValue(new DateTime(2000, 5, 23));
|
||||
|
||||
array.Add(text);
|
||||
array.Add(date);
|
||||
|
||||
JObject o = new JObject();
|
||||
o["MyArray"] = array;
|
||||
|
||||
string json = o.ToString();
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "MyArray": [
|
||||
// "Manual text",
|
||||
// "2000-05-23T00:00:00"
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class CreateReader
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o = new JObject
|
||||
{
|
||||
{"Cpu", "Intel"},
|
||||
{"Memory", 32},
|
||||
{
|
||||
"Drives", new JArray
|
||||
{
|
||||
"DVD",
|
||||
"SSD"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
JsonReader reader = o.CreateReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
Console.Write(reader.TokenType);
|
||||
if (reader.Value != null)
|
||||
Console.Write(" - " + reader.Value);
|
||||
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
// StartObject
|
||||
// PropertyName - Cpu
|
||||
// String - Intel
|
||||
// PropertyName - Memory
|
||||
// Integer - 32
|
||||
// PropertyName - Drives
|
||||
// StartArray
|
||||
// String - DVD
|
||||
// String - SSD
|
||||
// EndArray
|
||||
// EndObject
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class CreateWriter
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o = new JObject
|
||||
{
|
||||
{"name1", "value1"},
|
||||
{"name2", "value2"}
|
||||
};
|
||||
|
||||
JsonWriter writer = o.CreateWriter();
|
||||
writer.WritePropertyName("name3");
|
||||
writer.WriteStartArray();
|
||||
writer.WriteValue(1);
|
||||
writer.WriteValue(2);
|
||||
writer.WriteEndArray();
|
||||
|
||||
Console.WriteLine(o.ToString());
|
||||
// {
|
||||
// "name1": "value1",
|
||||
// "name2": "value2",
|
||||
// "name3": [
|
||||
// 1,
|
||||
// 2
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class DeepEquals
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JValue s1 = new JValue("A string");
|
||||
JValue s2 = new JValue("A string");
|
||||
JValue s3 = new JValue("A STRING");
|
||||
|
||||
Console.WriteLine(JToken.DeepEquals(s1, s2));
|
||||
// true
|
||||
|
||||
Console.WriteLine(JToken.DeepEquals(s2, s3));
|
||||
// false
|
||||
|
||||
JObject o1 = new JObject
|
||||
{
|
||||
{"Integer", 12345},
|
||||
{"String", "A string"},
|
||||
{"Items", new JArray(1, 2)}
|
||||
};
|
||||
|
||||
JObject o2 = new JObject
|
||||
{
|
||||
{"Integer", 12345},
|
||||
{"String", "A string"},
|
||||
{"Items", new JArray(1, 2)}
|
||||
};
|
||||
|
||||
Console.WriteLine(JToken.DeepEquals(o1, o2));
|
||||
// true
|
||||
|
||||
Console.WriteLine(JToken.DeepEquals(s1, o1["String"]));
|
||||
// true
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Web;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class DeserializeWithLinq
|
||||
{
|
||||
#region Types
|
||||
public class BlogPost
|
||||
{
|
||||
public string Title { get; set; }
|
||||
public string AuthorName { get; set; }
|
||||
public string AuthorTwitter { get; set; }
|
||||
public string Body { get; set; }
|
||||
public DateTime PostedDate { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"[
|
||||
{
|
||||
'Title': 'Json.NET is awesome!',
|
||||
'Author': {
|
||||
'Name': 'James Newton-King',
|
||||
'Twitter': '@JamesNK',
|
||||
'Picture': '/jamesnk.png'
|
||||
},
|
||||
'Date': '2013-01-23T19:30:00',
|
||||
'BodyHtml': '<h3>Title!</h3>\r\n<p>Content!</p>'
|
||||
}
|
||||
]";
|
||||
|
||||
JArray blogPostArray = JArray.Parse(json);
|
||||
|
||||
IList<BlogPost> blogPosts = blogPostArray.Select(p => new BlogPost
|
||||
{
|
||||
Title = (string) p["Title"],
|
||||
AuthorName = (string) p["Author"]["Name"],
|
||||
AuthorTwitter = (string) p["Author"]["Twitter"],
|
||||
PostedDate = (DateTime) p["Date"],
|
||||
Body = HttpUtility.HtmlDecode((string) p["BodyHtml"])
|
||||
}).ToList();
|
||||
|
||||
Console.WriteLine(blogPosts[0].Body);
|
||||
// <h3>Title!</h3>
|
||||
// <p>Content!</p>
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class FromObject
|
||||
{
|
||||
#region Types
|
||||
public class Computer
|
||||
{
|
||||
public string Cpu { get; set; }
|
||||
public int Memory { get; set; }
|
||||
public IList<string> Drives { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JValue i = (JValue)JToken.FromObject(12345);
|
||||
|
||||
Console.WriteLine(i.Type);
|
||||
// Integer
|
||||
Console.WriteLine(i.ToString());
|
||||
// 12345
|
||||
|
||||
JValue s = (JValue)JToken.FromObject("A string");
|
||||
|
||||
Console.WriteLine(s.Type);
|
||||
// String
|
||||
Console.WriteLine(s.ToString());
|
||||
// A string
|
||||
|
||||
Computer computer = new Computer
|
||||
{
|
||||
Cpu = "Intel",
|
||||
Memory = 32,
|
||||
Drives = new List<string>
|
||||
{
|
||||
"DVD",
|
||||
"SSD"
|
||||
}
|
||||
};
|
||||
|
||||
JObject o = (JObject)JToken.FromObject(computer);
|
||||
|
||||
Console.WriteLine(o.ToString());
|
||||
// {
|
||||
// "Cpu": "Intel",
|
||||
// "Memory": 32,
|
||||
// "Drives": [
|
||||
// "DVD",
|
||||
// "SSD"
|
||||
// ]
|
||||
// }
|
||||
|
||||
JArray a = (JArray)JToken.FromObject(computer.Drives);
|
||||
|
||||
Console.WriteLine(a.ToString());
|
||||
// [
|
||||
// "DVD",
|
||||
// "SSD"
|
||||
// ]
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class JObjectProperties
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o = new JObject
|
||||
{
|
||||
{ "name1", "value1" },
|
||||
{ "name2", "value2"}
|
||||
};
|
||||
|
||||
foreach (JProperty property in o.Properties())
|
||||
{
|
||||
Console.WriteLine(property.Name + " - " + property.Value);
|
||||
}
|
||||
// name1 - value1
|
||||
// name2 - value2
|
||||
|
||||
foreach (KeyValuePair<string, JToken> property in o)
|
||||
{
|
||||
Console.WriteLine(property.Key + " - " + property.Value);
|
||||
}
|
||||
// name1 - value1
|
||||
// name2 - value2
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class JValueCast
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JValue v1 = new JValue("1");
|
||||
int i = (int)v1;
|
||||
|
||||
Console.WriteLine(i);
|
||||
// 1
|
||||
|
||||
JValue v2 = new JValue(true);
|
||||
bool b = (bool)v2;
|
||||
|
||||
Console.WriteLine(b);
|
||||
// true
|
||||
|
||||
JValue v3 = new JValue("19.95");
|
||||
decimal d = (decimal)v3;
|
||||
|
||||
Console.WriteLine(d);
|
||||
// 19.95
|
||||
|
||||
JValue v4 = new JValue(new DateTime(2013, 1, 21));
|
||||
string s = (string)v4;
|
||||
|
||||
Console.WriteLine(s);
|
||||
// 01/21/2013 00:00:00
|
||||
|
||||
JValue v5 = new JValue("http://www.bing.com");
|
||||
Uri u = (Uri)v5;
|
||||
|
||||
Console.WriteLine(u);
|
||||
// http://www.bing.com/
|
||||
|
||||
JValue v6 = new JValue((object)null);
|
||||
u = (Uri)v6;
|
||||
|
||||
Console.WriteLine((u != null) ? u.ToString() : "{null}");
|
||||
// {null}
|
||||
|
||||
DateTime? dt = (DateTime?)v6;
|
||||
|
||||
Console.WriteLine((dt != null) ? dt.ToString() : "{null}");
|
||||
// {null}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class JValueValue
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JValue s = new JValue("A string value");
|
||||
|
||||
Console.WriteLine(s.Value.GetType().Name);
|
||||
// String
|
||||
Console.WriteLine(s.Value);
|
||||
// A string value
|
||||
|
||||
JValue u = new JValue(new Uri("http://www.google.com/"));
|
||||
|
||||
Console.WriteLine(u.Value.GetType().Name);
|
||||
// Uri
|
||||
Console.WriteLine(u.Value);
|
||||
// http://www.google.com/
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ModifyJson
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'channel': {
|
||||
'title': 'Star Wars',
|
||||
'link': 'http://www.starwars.com',
|
||||
'description': 'Star Wars blog.',
|
||||
'obsolete': 'Obsolete value',
|
||||
'item': []
|
||||
}
|
||||
}";
|
||||
|
||||
JObject rss = JObject.Parse(json);
|
||||
|
||||
JObject channel = (JObject)rss["channel"];
|
||||
|
||||
channel["title"] = ((string)channel["title"]).ToUpper();
|
||||
channel["description"] = ((string)channel["description"]).ToUpper();
|
||||
|
||||
channel.Property("obsolete").Remove();
|
||||
|
||||
channel.Property("description").AddAfterSelf(new JProperty("new", "New value"));
|
||||
|
||||
JArray item = (JArray) channel["item"];
|
||||
item.Add("Item 1");
|
||||
item.Add("Item 2");
|
||||
|
||||
Console.WriteLine(rss.ToString());
|
||||
// {
|
||||
// "channel": {
|
||||
// "title": "STAR WARS",
|
||||
// "link": "http://www.starwars.com",
|
||||
// "description": "STAR WARS BLOG.",
|
||||
// "new": "New value",
|
||||
// "item": [
|
||||
// "Item 1",
|
||||
// "Item 2"
|
||||
// ]
|
||||
// }
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ParseJsonAny
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JToken t1 = JToken.Parse("{}");
|
||||
|
||||
Console.WriteLine(t1.Type);
|
||||
// Object
|
||||
|
||||
JToken t2 = JToken.Parse("[]");
|
||||
|
||||
Console.WriteLine(t2.Type);
|
||||
// Array
|
||||
|
||||
JToken t3 = JToken.Parse("null");
|
||||
|
||||
Console.WriteLine(t3.Type);
|
||||
// Null
|
||||
|
||||
JToken t4 = JToken.Parse(@"'A string!'");
|
||||
|
||||
Console.WriteLine(t4.Type);
|
||||
// String
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ParseJsonArray
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"[
|
||||
'Small',
|
||||
'Medium',
|
||||
'Large'
|
||||
]";
|
||||
|
||||
JArray a = JArray.Parse(json);
|
||||
|
||||
Console.WriteLine(a.ToString());
|
||||
// [
|
||||
// "Small",
|
||||
// "Medium",
|
||||
// "Large"
|
||||
// ]
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ParseJsonObject
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
CPU: 'Intel',
|
||||
Drives: [
|
||||
'DVD read/writer',
|
||||
'500 gigabyte hard drive'
|
||||
]
|
||||
}";
|
||||
|
||||
JObject o = JObject.Parse(json);
|
||||
|
||||
Console.WriteLine(o.ToString());
|
||||
// {
|
||||
// "CPU": "Intel",
|
||||
// "Drives": [
|
||||
// "DVD read/writer",
|
||||
// "500 gigabyte hard drive"
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class QueryJson
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'channel': {
|
||||
'title': 'James Newton-King',
|
||||
'link': 'http://james.newtonking.com',
|
||||
'description': 'James Newton-King\'s blog.',
|
||||
'item': [
|
||||
{
|
||||
'title': 'Json.NET 1.3 + New license + Now on CodePlex',
|
||||
'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
|
||||
'link': 'http://james.newtonking.com/projects/json-net.aspx',
|
||||
'category': [
|
||||
'Json.NET',
|
||||
'CodePlex'
|
||||
]
|
||||
},
|
||||
{
|
||||
'title': 'LINQ to JSON beta',
|
||||
'description': 'Annoucing LINQ to JSON',
|
||||
'link': 'http://james.newtonking.com/projects/json-net.aspx',
|
||||
'category': [
|
||||
'Json.NET',
|
||||
'LINQ'
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}";
|
||||
|
||||
JObject rss = JObject.Parse(json);
|
||||
|
||||
string rssTitle = (string)rss["channel"]["title"];
|
||||
|
||||
Console.WriteLine(rssTitle);
|
||||
// James Newton-King
|
||||
|
||||
string itemTitle = (string)rss["channel"]["item"][0]["title"];
|
||||
|
||||
Console.WriteLine(itemTitle);
|
||||
// Json.NET 1.3 + New license + Now on CodePlex
|
||||
|
||||
JArray categories = (JArray)rss["channel"]["item"][0]["category"];
|
||||
|
||||
Console.WriteLine(categories);
|
||||
// [
|
||||
// "Json.NET",
|
||||
// "CodePlex"
|
||||
// ]
|
||||
|
||||
IList<string> categoriesText = categories.Select(c => (string)c).ToList();
|
||||
|
||||
Console.WriteLine(string.Join(", ", categoriesText));
|
||||
// Json.NET, CodePlex
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Web;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class QueryJsonDynamic
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"[
|
||||
{
|
||||
'Title': 'Json.NET is awesome!',
|
||||
'Author': {
|
||||
'Name': 'James Newton-King',
|
||||
'Twitter': '@JamesNK',
|
||||
'Picture': '/jamesnk.png'
|
||||
},
|
||||
'Date': '2013-01-23T19:30:00',
|
||||
'BodyHtml': '<h3>Title!</h3>\r\n<p>Content!</p>'
|
||||
}
|
||||
]";
|
||||
|
||||
dynamic blogPosts = JArray.Parse(json);
|
||||
|
||||
dynamic blogPost = blogPosts[0];
|
||||
|
||||
string title = blogPost.Title;
|
||||
|
||||
Console.WriteLine(title);
|
||||
// Json.NET is awesome!
|
||||
|
||||
string author = blogPost.Author.Name;
|
||||
|
||||
Console.WriteLine(author);
|
||||
// James Newton-King
|
||||
|
||||
DateTime postDate = blogPost.Date;
|
||||
|
||||
Console.WriteLine(postDate);
|
||||
// 23/01/2013 7:30:00 p.m.
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class QueryJsonLinq
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'channel': {
|
||||
'title': 'James Newton-King',
|
||||
'link': 'http://james.newtonking.com',
|
||||
'description': 'James Newton-King\'s blog.',
|
||||
'item': [
|
||||
{
|
||||
'title': 'Json.NET 1.3 + New license + Now on CodePlex',
|
||||
'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
|
||||
'link': 'http://james.newtonking.com/projects/json-net.aspx',
|
||||
'category': [
|
||||
'Json.NET',
|
||||
'CodePlex'
|
||||
]
|
||||
},
|
||||
{
|
||||
'title': 'LINQ to JSON beta',
|
||||
'description': 'Annoucing LINQ to JSON',
|
||||
'link': 'http://james.newtonking.com/projects/json-net.aspx',
|
||||
'category': [
|
||||
'Json.NET',
|
||||
'LINQ'
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}";
|
||||
|
||||
JObject rss = JObject.Parse(json);
|
||||
|
||||
var postTitles =
|
||||
from p in rss["channel"]["item"]
|
||||
select (string)p["title"];
|
||||
|
||||
foreach (var item in postTitles)
|
||||
{
|
||||
Console.WriteLine(item);
|
||||
}
|
||||
//LINQ to JSON beta
|
||||
//Json.NET 1.3 + New license + Now on CodePlex
|
||||
|
||||
var categories =
|
||||
from c in rss["channel"]["item"].Children()["category"].Values<string>()
|
||||
group c by c into g
|
||||
orderby g.Count() descending
|
||||
select new { Category = g.Key, Count = g.Count() };
|
||||
|
||||
foreach (var c in categories)
|
||||
{
|
||||
Console.WriteLine(c.Category + " - Count: " + c.Count);
|
||||
}
|
||||
//Json.NET - Count: 2
|
||||
//LINQ - Count: 1
|
||||
//CodePlex - Count: 1
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class QueryJsonSelectToken
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o = JObject.Parse(@"{
|
||||
'Stores': [
|
||||
'Lambton Quay',
|
||||
'Willis Street'
|
||||
],
|
||||
'Manufacturers': [
|
||||
{
|
||||
'Name': 'Acme Co',
|
||||
'Products': [
|
||||
{
|
||||
'Name': 'Anvil',
|
||||
'Price': 50
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
'Name': 'Contoso',
|
||||
'Products': [
|
||||
{
|
||||
'Name': 'Elbow Grease',
|
||||
'Price': 99.95
|
||||
},
|
||||
{
|
||||
'Name': 'Headlight Fluid',
|
||||
'Price': 4
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}");
|
||||
|
||||
string name = (string)o.SelectToken("Manufacturers[0].Name");
|
||||
|
||||
Console.WriteLine(name);
|
||||
// Acme Co
|
||||
|
||||
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
|
||||
|
||||
Console.WriteLine(productPrice);
|
||||
// 50
|
||||
|
||||
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
|
||||
|
||||
Console.WriteLine(productName);
|
||||
// Elbow Grease
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class QueryJsonSelectTokenWithLinq
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o = JObject.Parse(@"{
|
||||
'Stores': [
|
||||
'Lambton Quay',
|
||||
'Willis Street'
|
||||
],
|
||||
'Manufacturers': [
|
||||
{
|
||||
'Name': 'Acme Co',
|
||||
'Products': [
|
||||
{
|
||||
'Name': 'Anvil',
|
||||
'Price': 50
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
'Name': 'Contoso',
|
||||
'Products': [
|
||||
{
|
||||
'Name': 'Elbow Grease',
|
||||
'Price': 99.95
|
||||
},
|
||||
{
|
||||
'Name': 'Headlight Fluid',
|
||||
'Price': 4
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}");
|
||||
|
||||
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
|
||||
|
||||
Console.WriteLine(string.Join(", ", storeNames));
|
||||
// Lambton Quay, Willis Street
|
||||
|
||||
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name"))
|
||||
.Where(n => n != null).ToList();
|
||||
|
||||
Console.WriteLine(string.Join(", ", firstProductNames));
|
||||
// Headlight Fluid
|
||||
|
||||
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
|
||||
|
||||
Console.WriteLine(totalPrice);
|
||||
// 149.95
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using Newtonsoft.Json.Bson;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ReadJTokenFromBson
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
byte[] data = Convert.FromBase64String("KQAAAAJuYW1lMQAHAAAAdmFsdWUxAAJuYW1lMgAHAAAAdmFsdWUyAAA=");
|
||||
MemoryStream ms = new MemoryStream(data);
|
||||
|
||||
JObject o;
|
||||
using (BsonReader reader = new BsonReader(ms))
|
||||
{
|
||||
o = (JObject)JToken.ReadFrom(reader);
|
||||
}
|
||||
|
||||
string value = (string)o["name1"];
|
||||
|
||||
Console.WriteLine(value);
|
||||
// value1
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ReadJson
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));
|
||||
|
||||
// read JSON directly from a file
|
||||
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
|
||||
using (JsonTextReader reader = new JsonTextReader(file))
|
||||
{
|
||||
JObject o2 = (JObject) JToken.ReadFrom(reader);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Web;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class SerializeWithLinq
|
||||
{
|
||||
#region Types
|
||||
public class BlogPost
|
||||
{
|
||||
public string Title { get; set; }
|
||||
public string AuthorName { get; set; }
|
||||
public string AuthorTwitter { get; set; }
|
||||
public string Body { get; set; }
|
||||
public DateTime PostedDate { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
IList<BlogPost> blogPosts = new List<BlogPost>
|
||||
{
|
||||
new BlogPost
|
||||
{
|
||||
Title = "Json.NET is awesome!",
|
||||
AuthorName = "James Newton-King",
|
||||
AuthorTwitter = "JamesNK",
|
||||
PostedDate = new DateTime(2013, 1, 23, 19, 30, 0),
|
||||
Body = @"<h3>Title!</h3>
|
||||
<p>Content!</p>"
|
||||
}
|
||||
};
|
||||
|
||||
JArray blogPostsArray = new JArray(
|
||||
blogPosts.Select(p => new JObject
|
||||
{
|
||||
{"Title", p.Title},
|
||||
{
|
||||
"Author", new JObject
|
||||
{
|
||||
{"Name", p.AuthorName},
|
||||
{"Twitter", p.AuthorTwitter}
|
||||
}
|
||||
},
|
||||
{"Date", p.PostedDate},
|
||||
{"BodyHtml", HttpUtility.HtmlEncode(p.Body)},
|
||||
})
|
||||
);
|
||||
|
||||
Console.WriteLine(blogPostsArray.ToString());
|
||||
// [
|
||||
// {
|
||||
// "Title": "Json.NET is awesome!",
|
||||
// "Author": {
|
||||
// "Name": "James Newton-King",
|
||||
// "Twitter": "JamesNK"
|
||||
// },
|
||||
// "Date": "2013-01-23T19:30:00",
|
||||
// "BodyHtml": "<h3>Title!</h3>\r\n<p>Content!</p>"
|
||||
// }
|
||||
// ]
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ToObjectComplex
|
||||
{
|
||||
#region Types
|
||||
public class Person
|
||||
{
|
||||
public string Name { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'd': [
|
||||
{
|
||||
'Name': 'John Smith'
|
||||
},
|
||||
{
|
||||
'Name': 'Mike Smith'
|
||||
}
|
||||
]
|
||||
}";
|
||||
|
||||
JObject o = JObject.Parse(json);
|
||||
|
||||
JArray a = (JArray)o["d"];
|
||||
|
||||
IList<Person> person = a.ToObject<IList<Person>>();
|
||||
|
||||
Console.WriteLine(person[0].Name);
|
||||
// John Smith
|
||||
|
||||
Console.WriteLine(person[1].Name);
|
||||
// Mike Smith
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ToObjectGeneric
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JValue v1 = new JValue(true);
|
||||
|
||||
bool b = v1.ToObject<bool>();
|
||||
|
||||
Console.WriteLine(b);
|
||||
// true
|
||||
|
||||
int i = v1.ToObject<int>();
|
||||
|
||||
Console.WriteLine(i);
|
||||
// 1
|
||||
|
||||
string s = v1.ToObject<string>();
|
||||
|
||||
Console.WriteLine(s);
|
||||
// "True"
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ToObjectType
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JValue v1 = new JValue(true);
|
||||
|
||||
bool b = (bool)v1.ToObject(typeof(bool));
|
||||
|
||||
Console.WriteLine(b);
|
||||
// true
|
||||
|
||||
int i = (int)v1.ToObject(typeof(int));
|
||||
|
||||
Console.WriteLine(i);
|
||||
// 1
|
||||
|
||||
string s = (string)v1.ToObject(typeof(string));
|
||||
|
||||
Console.WriteLine(s);
|
||||
// "True"
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ToString
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o = JObject.Parse(@"{'string1':'value','integer2':99,'datetime3':'2000-05-23T00:00:00'}");
|
||||
|
||||
Console.WriteLine(o.ToString());
|
||||
// {
|
||||
// "string1": "value",
|
||||
// "integer2": 99,
|
||||
// "datetime3": "2000-05-23T00:00:00"
|
||||
// }
|
||||
|
||||
Console.WriteLine(o.ToString(Formatting.None));
|
||||
// {"string1":"value","integer2":99,"datetime3":"2000-05-23T00:00:00"}
|
||||
|
||||
Console.WriteLine(o.ToString(Formatting.None, new JavaScriptDateTimeConverter()));
|
||||
// {"string1":"value","integer2":99,"datetime3":new Date(959032800000)}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class ToStringJsonConverter
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o = JObject.Parse(@"{'string1':'value','integer2':99,'datetime3':'2000-05-23T00:00:00'}");
|
||||
|
||||
Console.WriteLine(o.ToString(Formatting.None, new JavaScriptDateTimeConverter()));
|
||||
// {"string1":"value","integer2":99,"datetime3":new Date(959032800000)}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Newtonsoft.Json.Bson;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class WriteJTokenToBson
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject o = new JObject
|
||||
{
|
||||
{"name1","value1"},
|
||||
{"name2","value2"}
|
||||
};
|
||||
|
||||
MemoryStream ms = new MemoryStream();
|
||||
using (BsonWriter writer = new BsonWriter(ms))
|
||||
{
|
||||
o.WriteTo(writer);
|
||||
}
|
||||
|
||||
string data = Convert.ToBase64String(ms.ToArray());
|
||||
|
||||
Console.WriteLine(data);
|
||||
// KQAAAAJuYW1lMQAHAAAAdmFsdWUxAAJuYW1lMgAHAAAAdmFsdWUyAAA=
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
|
||||
{
|
||||
public class WriteToJsonFile
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JObject videogameRatings = new JObject(
|
||||
new JProperty("Halo", 9),
|
||||
new JProperty("Starcraft", 9),
|
||||
new JProperty("Call of Duty", 7.5));
|
||||
|
||||
File.WriteAllText(@"c:\videogames.json", videogameRatings.ToString());
|
||||
|
||||
// write JSON directly to a file
|
||||
using (StreamWriter file = File.CreateText(@"c:\videogames.json"))
|
||||
using (JsonTextWriter writer = new JsonTextWriter(file))
|
||||
{
|
||||
videogameRatings.WriteTo(writer);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Schema;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
|
||||
{
|
||||
public class CreateJsonSchemaManually
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JsonSchema schema = new JsonSchema();
|
||||
schema.Type = JsonSchemaType.Object;
|
||||
schema.Properties = new Dictionary<string, JsonSchema>
|
||||
{
|
||||
{"name", new JsonSchema {Type = JsonSchemaType.String}},
|
||||
{
|
||||
"hobbies", new JsonSchema
|
||||
{
|
||||
Type = JsonSchemaType.Array,
|
||||
Items = new List<JsonSchema> { new JsonSchema {Type = JsonSchemaType.String} }
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
string schemaJson = schema.ToString();
|
||||
|
||||
Console.WriteLine(schemaJson);
|
||||
// {
|
||||
// "type": "object",
|
||||
// "properties": {
|
||||
// "name": {
|
||||
// "type": "string"
|
||||
// },
|
||||
// "hobbies": {
|
||||
// "type": "array",
|
||||
// "items": {
|
||||
// "type": "string"
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
JObject person = JObject.Parse(@"{
|
||||
'name': 'James',
|
||||
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
|
||||
}");
|
||||
|
||||
bool valid = person.IsValid(schema);
|
||||
|
||||
Console.WriteLine(valid);
|
||||
// true
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Schema;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
|
||||
{
|
||||
public class JTokenIsValid
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string schemaJson = @"{
|
||||
'description': 'A person',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type':'string'},
|
||||
'hobbies': {
|
||||
'type': 'array',
|
||||
'items': {'type':'string'}
|
||||
}
|
||||
}
|
||||
}";
|
||||
|
||||
JsonSchema schema = JsonSchema.Parse(schemaJson);
|
||||
|
||||
JObject person = JObject.Parse(@"{
|
||||
'name': 'James',
|
||||
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
|
||||
}");
|
||||
|
||||
bool valid = person.IsValid(schema);
|
||||
|
||||
Console.WriteLine(valid);
|
||||
// true
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Schema;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
|
||||
{
|
||||
public class JTokenIsValidWithMessages
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string schemaJson = @"{
|
||||
'description': 'A person',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type':'string'},
|
||||
'hobbies': {
|
||||
'type': 'array',
|
||||
'items': {'type':'string'}
|
||||
}
|
||||
}
|
||||
}";
|
||||
|
||||
JsonSchema schema = JsonSchema.Parse(schemaJson);
|
||||
|
||||
JObject person = JObject.Parse(@"{
|
||||
'name': null,
|
||||
'hobbies': ['Invalid content', 0.123456789]
|
||||
}");
|
||||
|
||||
IList<string> messages;
|
||||
bool valid = person.IsValid(schema, out messages);
|
||||
|
||||
Console.WriteLine(valid);
|
||||
// false
|
||||
|
||||
foreach (string message in messages)
|
||||
{
|
||||
Console.WriteLine(message);
|
||||
}
|
||||
// Invalid type. Expected String but got Null. Line 2, position 21.
|
||||
// Invalid type. Expected String but got Float. Line 3, position 51.
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Schema;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
|
||||
{
|
||||
public class JTokenValidateWithEvent
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string schemaJson = @"{
|
||||
'description': 'A person',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type':'string'},
|
||||
'hobbies': {
|
||||
'type': 'array',
|
||||
'items': {'type':'string'}
|
||||
}
|
||||
}
|
||||
}";
|
||||
|
||||
JsonSchema schema = JsonSchema.Parse(schemaJson);
|
||||
|
||||
JObject person = JObject.Parse(@"{
|
||||
'name': null,
|
||||
'hobbies': ['Invalid content', 0.123456789]
|
||||
}");
|
||||
|
||||
IList<string> messages = new List<string>();
|
||||
ValidationEventHandler validationEventHandler = (sender, args) => { messages.Add(args.Message); };
|
||||
|
||||
person.Validate(schema, validationEventHandler);
|
||||
|
||||
foreach (string message in messages)
|
||||
{
|
||||
Console.WriteLine(message);
|
||||
}
|
||||
// Invalid type. Expected String but got Null. Line 2, position 21.
|
||||
// Invalid type. Expected String but got Float. Line 3, position 51.
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Schema;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
|
||||
{
|
||||
public class JsonSchemaParse
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string schemaJson = @"{
|
||||
'description': 'A person',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type':'string'},
|
||||
'hobbies': {
|
||||
'type': 'array',
|
||||
'items': {'type':'string'}
|
||||
}
|
||||
}
|
||||
}";
|
||||
|
||||
JsonSchema schema = JsonSchema.Parse(schemaJson);
|
||||
|
||||
Console.WriteLine(schema.Type);
|
||||
// Object
|
||||
|
||||
foreach (var property in schema.Properties)
|
||||
{
|
||||
Console.WriteLine(property.Key + " - " + property.Value.Type);
|
||||
}
|
||||
// name - String
|
||||
// hobbies - Array
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
using Newtonsoft.Json.Schema;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
|
||||
{
|
||||
public class JsonValidatingReaderAndSerializer
|
||||
{
|
||||
#region Types
|
||||
public class Person
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public IList<string> Hobbies { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string schemaJson = @"{
|
||||
'description': 'A person',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type':'string'},
|
||||
'hobbies': {
|
||||
'type': 'array',
|
||||
'items': {'type':'string'}
|
||||
}
|
||||
}
|
||||
}";
|
||||
|
||||
string json = @"{
|
||||
'name': 'James',
|
||||
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
|
||||
}";
|
||||
|
||||
JsonTextReader reader = new JsonTextReader(new StringReader(json));
|
||||
|
||||
JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
|
||||
validatingReader.Schema = JsonSchema.Parse(schemaJson);
|
||||
|
||||
IList<string> messages = new List<string>();
|
||||
validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);
|
||||
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
Person p = serializer.Deserialize<Person>(validatingReader);
|
||||
|
||||
Console.WriteLine(p.Name);
|
||||
// James
|
||||
|
||||
bool isValid = (messages.Count == 0);
|
||||
|
||||
Console.WriteLine(isValid);
|
||||
// true
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Newtonsoft.Json.Schema;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
|
||||
{
|
||||
public class LoadJsonSchemaFromFile
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
// read file into a string and parse JsonSchema from the string
|
||||
JsonSchema schema1 = JsonSchema.Parse(File.ReadAllText(@"c:\schema.json"));
|
||||
|
||||
// read JsonSchema directly from a file
|
||||
using (StreamReader file = File.OpenText(@"c:\schema.json"))
|
||||
using (JsonTextReader reader = new JsonTextReader(file))
|
||||
{
|
||||
JsonSchema schema2 = JsonSchema.Read(reader);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Schema;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
|
||||
{
|
||||
public class RefJsonSchemaResolver
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string schemaJson;
|
||||
JsonSchemaResolver resolver = new JsonSchemaResolver();
|
||||
|
||||
schemaJson = @"{
|
||||
'id': 'person',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type':'string'},
|
||||
'age': {'type':'integer'}
|
||||
}
|
||||
}";
|
||||
|
||||
JsonSchema personSchema = JsonSchema.Parse(schemaJson, resolver);
|
||||
|
||||
schemaJson = @"{
|
||||
'id': 'employee',
|
||||
'type': 'object',
|
||||
'extends': {'$ref':'person'},
|
||||
'properties': {
|
||||
'salary': {'type':'number'},
|
||||
'jobTitle': {'type':'string'}
|
||||
}
|
||||
}";
|
||||
|
||||
JsonSchema employeeSchema = JsonSchema.Parse(schemaJson, resolver);
|
||||
|
||||
string json = @"{
|
||||
'name': 'James',
|
||||
'age': 29,
|
||||
'salary': 9000.01,
|
||||
'jobTitle': 'Junior Vice President'
|
||||
}";
|
||||
|
||||
JObject employee = JObject.Parse(json);
|
||||
|
||||
bool valid = employee.IsValid(employeeSchema);
|
||||
|
||||
Console.WriteLine(valid);
|
||||
// true
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Newtonsoft.Json.Schema;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
|
||||
{
|
||||
public class SaveJsonSchemaToFile
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JsonSchema schema = JsonSchema.Parse(@"{'type': 'object'}");
|
||||
|
||||
// serialize JsonSchema to a string and then write string to a file
|
||||
File.WriteAllText(@"c:\schema.json", schema.ToString());
|
||||
|
||||
// serialize JsonSchema directly to a file
|
||||
using (StreamWriter file = File.CreateText(@"c:\schema.json"))
|
||||
using (JsonTextWriter writer = new JsonTextWriter(file))
|
||||
{
|
||||
schema.WriteTo(writer);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class CustomContractResolver
|
||||
{
|
||||
#region Types
|
||||
public class DynamicContractResolver : DefaultContractResolver
|
||||
{
|
||||
private readonly char _startingWithChar;
|
||||
public DynamicContractResolver(char startingWithChar)
|
||||
{
|
||||
_startingWithChar = startingWithChar;
|
||||
}
|
||||
|
||||
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
|
||||
{
|
||||
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
|
||||
|
||||
// only serializer properties that start with the specified character
|
||||
properties =
|
||||
properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
|
||||
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
|
||||
public class Person
|
||||
{
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
|
||||
public string FullName
|
||||
{
|
||||
get { return FirstName + " " + LastName; }
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Person person = new Person
|
||||
{
|
||||
FirstName = "Dennis",
|
||||
LastName = "Deepwater-Diver"
|
||||
};
|
||||
|
||||
string startingWithF = JsonConvert.SerializeObject(person, Formatting.Indented,
|
||||
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('F') });
|
||||
|
||||
Console.WriteLine(startingWithF);
|
||||
// {
|
||||
// "FirstName": "Dennis",
|
||||
// "FullName": "Dennis Deepwater-Diver"
|
||||
// }
|
||||
|
||||
string startingWithL = JsonConvert.SerializeObject(person, Formatting.Indented,
|
||||
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('L') });
|
||||
|
||||
Console.WriteLine(startingWithL);
|
||||
// {
|
||||
// "LastName": "Deepwater-Diver"
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class CustomJsonConverter
|
||||
{
|
||||
#region Types
|
||||
public class KeysJsonConverter : JsonConverter
|
||||
{
|
||||
private readonly Type[] _types;
|
||||
|
||||
public KeysJsonConverter(params Type[] types)
|
||||
{
|
||||
_types = types;
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
JToken t = JToken.FromObject(value);
|
||||
|
||||
if (t.Type != JTokenType.Object)
|
||||
{
|
||||
t.WriteTo(writer);
|
||||
}
|
||||
else
|
||||
{
|
||||
JObject o = (JObject)t;
|
||||
IList<string> propertyNames = o.Properties().Select(p => p.Name).ToList();
|
||||
|
||||
o.AddFirst(new JProperty("Keys", new JArray(propertyNames)));
|
||||
|
||||
o.WriteTo(writer);
|
||||
}
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
|
||||
}
|
||||
|
||||
public override bool CanRead
|
||||
{
|
||||
get { return false; }
|
||||
}
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return _types.Any(t => t == objectType);
|
||||
}
|
||||
}
|
||||
|
||||
public class Employee
|
||||
{
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
public IList<string> Roles { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Employee employee = new Employee
|
||||
{
|
||||
FirstName = "James",
|
||||
LastName = "Newton-King",
|
||||
Roles = new List<string>
|
||||
{
|
||||
"Admin"
|
||||
}
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(employee, Formatting.Indented, new KeysJsonConverter(typeof(Employee)));
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "Keys": [
|
||||
// "FirstName",
|
||||
// "LastName",
|
||||
// "Roles"
|
||||
// ],
|
||||
// "FirstName": "James",
|
||||
// "LastName": "Newton-King",
|
||||
// "Roles": [
|
||||
// "Admin"
|
||||
// ]
|
||||
// }
|
||||
|
||||
Employee newEmployee = JsonConvert.DeserializeObject<Employee>(json, new KeysJsonConverter(typeof(Employee)));
|
||||
|
||||
Console.WriteLine(newEmployee.FirstName);
|
||||
// James
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class CustomTraceWriter
|
||||
{
|
||||
#region Types
|
||||
public class NLogTraceWriter : ITraceWriter
|
||||
{
|
||||
private static readonly Logger Logger = LogManager.GetLogger("NLogTraceWriter");
|
||||
|
||||
public TraceLevel LevelFilter
|
||||
{
|
||||
// trace all messages. nlog can handle filtering
|
||||
get { return TraceLevel.Verbose; }
|
||||
}
|
||||
|
||||
public void Trace(TraceLevel level, string message, Exception ex)
|
||||
{
|
||||
LogEventInfo logEvent = new LogEventInfo
|
||||
{
|
||||
Message = message,
|
||||
Level = GetLogLevel(level),
|
||||
Exception = ex
|
||||
};
|
||||
|
||||
// log Json.NET message to NLog
|
||||
Logger.Log(logEvent);
|
||||
}
|
||||
|
||||
private LogLevel GetLogLevel(TraceLevel level)
|
||||
{
|
||||
switch (level)
|
||||
{
|
||||
case TraceLevel.Error:
|
||||
return LogLevel.Error;
|
||||
case TraceLevel.Warning:
|
||||
return LogLevel.Warn;
|
||||
case TraceLevel.Info:
|
||||
return LogLevel.Info;
|
||||
case TraceLevel.Off:
|
||||
return LogLevel.Off;
|
||||
default:
|
||||
return LogLevel.Trace;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
IList<string> countries = new List<string>
|
||||
{
|
||||
"New Zealand",
|
||||
"Australia",
|
||||
"Denmark",
|
||||
"China"
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(countries, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
TraceWriter = new NLogTraceWriter()
|
||||
});
|
||||
|
||||
Console.WriteLine(json);
|
||||
// [
|
||||
// "New Zealand",
|
||||
// "Australia",
|
||||
// "Denmark",
|
||||
// "China"
|
||||
// ]
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DataContractAndDataMember
|
||||
{
|
||||
#region Usage
|
||||
[DataContract]
|
||||
public class File
|
||||
{
|
||||
// excluded from serialization
|
||||
// does not have DataMemberAttribute
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[DataMember]
|
||||
public string Name { get; set; }
|
||||
[DataMember]
|
||||
public int Size { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
File file = new File
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "ImportantLegalDocuments.docx",
|
||||
Size = 50*1024
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(file, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "Name": "ImportantLegalDocuments.docx",
|
||||
// "Size": 51200
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DefaultValueAttributeIgnore
|
||||
{
|
||||
#region Types
|
||||
public class Customer
|
||||
{
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
|
||||
[DefaultValue(" ")]
|
||||
public string FullName
|
||||
{
|
||||
get { return FirstName + " " + LastName; }
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Customer customer = new Customer();
|
||||
|
||||
string jsonIncludeDefaultValues = JsonConvert.SerializeObject(customer, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(jsonIncludeDefaultValues);
|
||||
// {
|
||||
// "FirstName": null,
|
||||
// "LastName": null,
|
||||
// "FullName": " "
|
||||
// }
|
||||
|
||||
string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(customer, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
DefaultValueHandling = DefaultValueHandling.Ignore
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonIgnoreDefaultValues);
|
||||
// {}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DefaultValueHandlingIgnore
|
||||
{
|
||||
#region Types
|
||||
public class Person
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public int Age { get; set; }
|
||||
public Person Partner { get; set; }
|
||||
public decimal? Salary { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Person person = new Person();
|
||||
|
||||
string jsonIncludeDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(jsonIncludeDefaultValues);
|
||||
// {
|
||||
// "Name": null,
|
||||
// "Age": 0,
|
||||
// "Partner": null,
|
||||
// "Salary": null
|
||||
// }
|
||||
|
||||
string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
DefaultValueHandling = DefaultValueHandling.Ignore
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonIgnoreDefaultValues);
|
||||
// {}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DeserializeAnonymousType
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{'Name':'James'}";
|
||||
|
||||
var customerDefinition = new {Name = ""};
|
||||
|
||||
var customer = JsonConvert.DeserializeAnonymousType(json, customerDefinition);
|
||||
|
||||
Console.WriteLine(customer.Name);
|
||||
// James
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DeserializeCollection
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"['Starcraft','Halo','Legend of Zelda']";
|
||||
|
||||
List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json);
|
||||
|
||||
Console.WriteLine(string.Join(", ", videogames));
|
||||
// Starcraft, Halo, Legend of Zelda
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DeserializeConstructorHandling
|
||||
{
|
||||
#region Types
|
||||
public class Website
|
||||
{
|
||||
public string Url { get; set; }
|
||||
|
||||
private Website()
|
||||
{
|
||||
}
|
||||
|
||||
public Website(Website website)
|
||||
{
|
||||
if (website == null)
|
||||
throw new ArgumentNullException("website");
|
||||
|
||||
Url = website.Url;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{'Url':'http://www.google.com'}";
|
||||
|
||||
try
|
||||
{
|
||||
JsonConvert.DeserializeObject<Website>(json);
|
||||
}
|
||||
catch (TargetInvocationException ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
// Value cannot be null.
|
||||
// Parameter name: website
|
||||
}
|
||||
|
||||
Website website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings
|
||||
{
|
||||
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
|
||||
});
|
||||
|
||||
Console.WriteLine(website.Url);
|
||||
// http://www.google.com
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DeserializeCustomCreationConverter
|
||||
{
|
||||
#region Types
|
||||
public class Person
|
||||
{
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
public DateTime BirthDate { get; set; }
|
||||
}
|
||||
|
||||
public class Employee : Person
|
||||
{
|
||||
public string Department { get; set; }
|
||||
public string JobTitle { get; set; }
|
||||
}
|
||||
|
||||
public class PersonConverter : CustomCreationConverter<Person>
|
||||
{
|
||||
public override Person Create(Type objectType)
|
||||
{
|
||||
return new Employee();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'Department': 'Furniture',
|
||||
'JobTitle': 'Carpenter',
|
||||
'FirstName': 'John',
|
||||
'LastName': 'Joinery',
|
||||
'BirthDate': '1983-02-02T00:00:00'
|
||||
}";
|
||||
|
||||
Person person = JsonConvert.DeserializeObject<Person>(json, new PersonConverter());
|
||||
|
||||
Console.WriteLine(person.GetType().Name);
|
||||
// Employee
|
||||
|
||||
Employee employee = (Employee) person;
|
||||
|
||||
Console.WriteLine(employee.JobTitle);
|
||||
// Capenter
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DeserializeDataSet
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'Table1': [
|
||||
{
|
||||
'id': 0,
|
||||
'item': 'item 0'
|
||||
},
|
||||
{
|
||||
'id': 1,
|
||||
'item': 'item 1'
|
||||
}
|
||||
]
|
||||
}";
|
||||
|
||||
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
|
||||
|
||||
DataTable dataTable = dataSet.Tables["Table1"];
|
||||
|
||||
Console.WriteLine(dataTable.Rows.Count);
|
||||
// 2
|
||||
|
||||
foreach (DataRow row in dataTable.Rows)
|
||||
{
|
||||
Console.WriteLine(row["id"] + " - " + row["item"]);
|
||||
}
|
||||
// 0 - item 0
|
||||
// 1 - item 1
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DeserializeDictionary
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'href': '/account/login.aspx',
|
||||
'target': '_blank'
|
||||
}";
|
||||
|
||||
Dictionary<string, string> htmlAttributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
|
||||
|
||||
Console.WriteLine(htmlAttributes["href"]);
|
||||
// /account/login.aspx
|
||||
|
||||
Console.WriteLine(htmlAttributes["target"]);
|
||||
// _blank
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DeserializeMissingMemberHandling
|
||||
{
|
||||
#region Types
|
||||
public class Account
|
||||
{
|
||||
public string FullName { get; set; }
|
||||
public bool Deleted { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'FullName': 'Dan Deleted',
|
||||
'Deleted': true,
|
||||
'DeletedDate': '2013-01-20T00:00:00'
|
||||
}";
|
||||
|
||||
try
|
||||
{
|
||||
JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings
|
||||
{
|
||||
MissingMemberHandling = MissingMemberHandling.Error
|
||||
});
|
||||
}
|
||||
catch (JsonSerializationException ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
// Could not find member 'DeletedDate' on object of type 'Account'. Path 'DeletedDate', line 4, position 23.
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DeserializeObject
|
||||
{
|
||||
#region Types
|
||||
public class Account
|
||||
{
|
||||
public string Email { get; set; }
|
||||
public bool Active { get; set; }
|
||||
public DateTime CreatedDate { get; set; }
|
||||
public IList<string> Roles { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'Email': 'james@example.com',
|
||||
'Active': true,
|
||||
'CreatedDate': '2013-01-20T00:00:00Z',
|
||||
'Roles': [
|
||||
'User',
|
||||
'Admin'
|
||||
]
|
||||
}";
|
||||
|
||||
Account account = JsonConvert.DeserializeObject<Account>(json);
|
||||
|
||||
Console.WriteLine(account.Email);
|
||||
// james@example.com
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DeserializeObjectCreationHandling
|
||||
{
|
||||
#region Types
|
||||
public class UserViewModel
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public IList<string> Offices { get; private set; }
|
||||
|
||||
public UserViewModel()
|
||||
{
|
||||
Offices = new List<string>
|
||||
{
|
||||
"Auckland",
|
||||
"Wellington",
|
||||
"Christchurch"
|
||||
};
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'Name': 'James',
|
||||
'Offices': [
|
||||
'Auckland',
|
||||
'Wellington',
|
||||
'Christchurch'
|
||||
]
|
||||
}";
|
||||
|
||||
UserViewModel model1 = JsonConvert.DeserializeObject<UserViewModel>(json);
|
||||
|
||||
foreach (string office in model1.Offices)
|
||||
{
|
||||
Console.WriteLine(office);
|
||||
}
|
||||
// Auckland
|
||||
// Wellington
|
||||
// Christchurch
|
||||
// Auckland
|
||||
// Wellington
|
||||
// Christchurch
|
||||
|
||||
UserViewModel model2 = JsonConvert.DeserializeObject<UserViewModel>(json, new JsonSerializerSettings
|
||||
{
|
||||
ObjectCreationHandling = ObjectCreationHandling.Replace
|
||||
});
|
||||
|
||||
foreach (string office in model2.Offices)
|
||||
{
|
||||
Console.WriteLine(office);
|
||||
}
|
||||
// Auckland
|
||||
// Wellington
|
||||
// Christchurch
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using File = System.IO.File;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class DeserializeWithJsonSerializerFromFile
|
||||
{
|
||||
#region Types
|
||||
public class Movie
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public int Year { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
// read file into a string and deserialize JSON to a type
|
||||
Movie movie1 = JsonConvert.DeserializeObject<Movie>(File.ReadAllText(@"c:\movie.json"));
|
||||
|
||||
// deserialize JSON directly from a file
|
||||
using (StreamReader file = File.OpenText(@"c:\movie.json"))
|
||||
{
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
Movie movie2 = (Movie)serializer.Deserialize(file, typeof (Movie));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class ErrorHandlingAttribute
|
||||
{
|
||||
#region Types
|
||||
public class Employee
|
||||
{
|
||||
private List<string> _roles;
|
||||
|
||||
public string Name { get; set; }
|
||||
public int Age { get; set; }
|
||||
public List<string> Roles
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_roles == null)
|
||||
throw new Exception("Roles not loaded!");
|
||||
|
||||
return _roles;
|
||||
}
|
||||
set { _roles = value; }
|
||||
}
|
||||
public string Title { get; set; }
|
||||
|
||||
[OnError]
|
||||
internal void OnError(StreamingContext context, ErrorContext errorContext)
|
||||
{
|
||||
errorContext.Handled = true;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Employee person = new Employee
|
||||
{
|
||||
Name = "George Michael Bluth",
|
||||
Age = 16,
|
||||
Roles = null,
|
||||
Title = "Mister Manager"
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(person, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "Name": "George Michael Bluth",
|
||||
// "Age": 16,
|
||||
// "Title": "Mister Manager"
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class ErrorHandlingEvent
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
List<string> errors = new List<string>();
|
||||
|
||||
List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[
|
||||
'2009-09-09T00:00:00Z',
|
||||
'I am not a date and will error!',
|
||||
[
|
||||
1
|
||||
],
|
||||
'1977-02-20T00:00:00Z',
|
||||
null,
|
||||
'2000-12-01T00:00:00Z'
|
||||
]",
|
||||
new JsonSerializerSettings
|
||||
{
|
||||
Error = delegate(object sender, ErrorEventArgs args)
|
||||
{
|
||||
errors.Add(args.ErrorContext.Error.Message);
|
||||
args.ErrorContext.Handled = true;
|
||||
},
|
||||
Converters = { new IsoDateTimeConverter() }
|
||||
});
|
||||
|
||||
// 2009-09-09T00:00:00Z
|
||||
// 1977-02-20T00:00:00Z
|
||||
// 2000-12-01T00:00:00Z
|
||||
|
||||
// The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
|
||||
// Unexpected token parsing date. Expected String, got StartArray.
|
||||
// Cannot convert null value to System.DateTime.
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class JsonConverterAttributeClass
|
||||
{
|
||||
#region Types
|
||||
public class UserConverter : JsonConverter
|
||||
{
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
User user = (User) value;
|
||||
|
||||
writer.WriteValue(user.UserName);
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
User user = new User();
|
||||
user.UserName = (string)reader.Value;
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return objectType == typeof (User);
|
||||
}
|
||||
}
|
||||
|
||||
[JsonConverter(typeof(UserConverter))]
|
||||
public class User
|
||||
{
|
||||
public string UserName { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
User user = new User
|
||||
{
|
||||
UserName = @"domain\username"
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(user, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// "domain\\username"
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class JsonConverterAttributeProperty
|
||||
{
|
||||
#region Types
|
||||
public enum UserStatus
|
||||
{
|
||||
NotConfirmed,
|
||||
Active,
|
||||
Deleted
|
||||
}
|
||||
|
||||
public class User
|
||||
{
|
||||
public string UserName { get; set; }
|
||||
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
public UserStatus Status { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
User user = new User
|
||||
{
|
||||
UserName = @"domain\username",
|
||||
Status = UserStatus.Deleted
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(user, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "UserName": "domain\\username",
|
||||
// "Status": "Deleted"
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class JsonObjectAttributeOptIn
|
||||
{
|
||||
#region Types
|
||||
[JsonObject(MemberSerialization.OptIn)]
|
||||
public class File
|
||||
{
|
||||
// excluded from serialization
|
||||
// does not have JsonPropertyAttribute
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[JsonProperty]
|
||||
public string Name { get; set; }
|
||||
[JsonProperty]
|
||||
public int Size { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
File file = new File
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "ImportantLegalDocuments.docx",
|
||||
Size = 50 * 1024
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(file, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "Name": "ImportantLegalDocuments.docx",
|
||||
// "Size": 51200
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class JsonObjectAttributeOverrideIEnumerable
|
||||
{
|
||||
#region Types
|
||||
[JsonObject]
|
||||
public class Directory : IEnumerable<string>
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public IList<string> Files { get; set; }
|
||||
|
||||
public Directory()
|
||||
{
|
||||
Files = new List<string>();
|
||||
}
|
||||
|
||||
public IEnumerator<string> GetEnumerator()
|
||||
{
|
||||
return Files.GetEnumerator();
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return GetEnumerator();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Directory directory = new Directory
|
||||
{
|
||||
Name = "My Documents",
|
||||
Files =
|
||||
{
|
||||
"ImportantLegalDocuments.docx",
|
||||
"WiseFinancalAdvice.xlsx"
|
||||
}
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(directory, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "Name": "My Documents",
|
||||
// "Files": [
|
||||
// "ImportantLegalDocuments.docx",
|
||||
// "WiseFinancalAdvice.xlsx"
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class JsonPropertyItemLevelSetting
|
||||
{
|
||||
#region Types
|
||||
public class Business
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
[JsonProperty(ItemIsReference = true)]
|
||||
public IList<Employee> Employees { get; set; }
|
||||
}
|
||||
|
||||
public class Employee
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
[JsonProperty(IsReference = true)]
|
||||
public Employee Manager { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Employee manager = new Employee
|
||||
{
|
||||
Name = "George-Michael"
|
||||
};
|
||||
Employee worker = new Employee
|
||||
{
|
||||
Name = "Maeby",
|
||||
Manager = manager
|
||||
};
|
||||
|
||||
Business business = new Business
|
||||
{
|
||||
Name = "Acme Ltd.",
|
||||
Employees = new List<Employee>
|
||||
{
|
||||
manager,
|
||||
worker
|
||||
}
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(business, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "Name": "Acme Ltd.",
|
||||
// "Employees": [
|
||||
// {
|
||||
// "$id": "1",
|
||||
// "Name": "George-Michael",
|
||||
// "Manager": null
|
||||
// },
|
||||
// {
|
||||
// "$id": "2",
|
||||
// "Name": "Maeby",
|
||||
// "Manager": {
|
||||
// "$ref": "1"
|
||||
// }
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class JsonPropertyName
|
||||
{
|
||||
#region Types
|
||||
public class Videogame
|
||||
{
|
||||
[JsonProperty("name")]
|
||||
public string Name { get; set; }
|
||||
|
||||
[JsonProperty("release_date")]
|
||||
public DateTime ReleaseDate { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Videogame starcraft = new Videogame
|
||||
{
|
||||
Name = "Starcraft",
|
||||
ReleaseDate = new DateTime(1998, 1, 1)
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(starcraft, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "name": "Starcraft",
|
||||
// "release_date": "1998-01-01T00:00:00"
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class JsonPropertyOrder
|
||||
{
|
||||
#region Types
|
||||
public class Account
|
||||
{
|
||||
public string EmailAddress { get; set; }
|
||||
|
||||
// appear last
|
||||
[JsonProperty(Order = 1)]
|
||||
public bool Deleted { get; set; }
|
||||
[JsonProperty(Order = 2)]
|
||||
public DateTime DeletedDate { get; set; }
|
||||
|
||||
public DateTime CreatedDate { get; set; }
|
||||
public DateTime UpdatedDate { get; set; }
|
||||
|
||||
// appear first
|
||||
[JsonProperty(Order = -2)]
|
||||
public string FullName { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Account account = new Account
|
||||
{
|
||||
FullName = "Aaron Account",
|
||||
EmailAddress = "aaron@example.com",
|
||||
Deleted = true,
|
||||
DeletedDate = new DateTime(2013, 1, 25),
|
||||
UpdatedDate = new DateTime(2013, 1, 25),
|
||||
CreatedDate = new DateTime(2010, 10, 1)
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "FullName": "Aaron Account",
|
||||
// "EmailAddress": "aaron@example.com",
|
||||
// "CreatedDate": "2010-10-01T00:00:00",
|
||||
// "UpdatedDate": "2013-01-25T00:00:00",
|
||||
// "Deleted": true,
|
||||
// "DeletedDate": "2013-01-25T00:00:00"
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class JsonPropertyPropertyLevelSetting
|
||||
{
|
||||
#region Types
|
||||
public class Vessel
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string Class { get; set; }
|
||||
|
||||
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
|
||||
public DateTime? LaunchDate { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Vessel vessel = new Vessel
|
||||
{
|
||||
Name = "Red October",
|
||||
Class = "Typhoon"
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(vessel, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "Name": "Red October",
|
||||
// "Class": "Typhoon"
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class JsonPropertyRequired
|
||||
{
|
||||
#region Types
|
||||
public class Videogame
|
||||
{
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Name { get; set; }
|
||||
|
||||
[JsonProperty(Required = Required.AllowNull)]
|
||||
public DateTime? ReleaseDate { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'Name': 'Starcraft III',
|
||||
'ReleaseDate': null
|
||||
}";
|
||||
|
||||
Videogame starcraft = JsonConvert.DeserializeObject<Videogame>(json);
|
||||
|
||||
Console.WriteLine(starcraft.Name);
|
||||
// Starcraft III
|
||||
|
||||
Console.WriteLine(starcraft.ReleaseDate);
|
||||
// null
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class MaxDepth
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"[
|
||||
[
|
||||
[
|
||||
'1',
|
||||
'Two',
|
||||
'III'
|
||||
]
|
||||
]
|
||||
]";
|
||||
|
||||
try
|
||||
{
|
||||
JsonConvert.DeserializeObject<List<IList<IList<string>>>>(json, new JsonSerializerSettings
|
||||
{
|
||||
MaxDepth = 2
|
||||
});
|
||||
}
|
||||
catch (JsonReaderException ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
// The reader's MaxDepth of 2 has been exceeded. Path '[0][0]', line 3, position 12.
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class NullValueHandlingIgnore
|
||||
{
|
||||
#region Types
|
||||
public class Person
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public int Age { get; set; }
|
||||
public Person Partner { get; set; }
|
||||
public decimal? Salary { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Person person = new Person
|
||||
{
|
||||
Name = "Nigal Newborn",
|
||||
Age = 1
|
||||
};
|
||||
|
||||
string jsonIncludeNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(jsonIncludeNullValues);
|
||||
// {
|
||||
// "Name": "Nigal Newborn",
|
||||
// "Age": 1,
|
||||
// "Partner": null,
|
||||
// "Salary": null
|
||||
// }
|
||||
|
||||
string jsonIgnoreNullValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
NullValueHandling = NullValueHandling.Ignore
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonIgnoreNullValues);
|
||||
// {
|
||||
// "Name": "Nigal Newborn",
|
||||
// "Age": 1
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class PopulateObject
|
||||
{
|
||||
#region Types
|
||||
public class Account
|
||||
{
|
||||
public string Email { get; set; }
|
||||
public bool Active { get; set; }
|
||||
public DateTime CreatedDate { get; set; }
|
||||
public IList<string> Roles { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Account account = new Account
|
||||
{
|
||||
Email = "james@example.com",
|
||||
Active = true,
|
||||
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
|
||||
Roles = new List<string>
|
||||
{
|
||||
"User",
|
||||
"Admin"
|
||||
}
|
||||
};
|
||||
|
||||
string json = @"{
|
||||
'Active': false,
|
||||
'Roles': [
|
||||
'Expired'
|
||||
]
|
||||
}";
|
||||
|
||||
JsonConvert.PopulateObject(json, account);
|
||||
|
||||
Console.WriteLine(account.Email);
|
||||
// james@example.com
|
||||
|
||||
Console.WriteLine(account.Active);
|
||||
// false
|
||||
|
||||
Console.WriteLine(string.Join(", ", account.Roles));
|
||||
// User, Admin, Expired
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class PreserveReferencesHandlingObject
|
||||
{
|
||||
#region Types
|
||||
public class Directory
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public Directory Parent { get; set; }
|
||||
public IList<File> Files { get; set; }
|
||||
}
|
||||
|
||||
public class File
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public Directory Parent { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Directory root = new Directory { Name = "Root" };
|
||||
Directory documents = new Directory { Name = "My Documents", Parent = root };
|
||||
|
||||
File file = new File { Name = "ImportantLegalDocument.docx", Parent = documents };
|
||||
|
||||
documents.Files = new List<File> { file };
|
||||
|
||||
try
|
||||
{
|
||||
JsonConvert.SerializeObject(documents, Formatting.Indented);
|
||||
}
|
||||
catch (JsonSerializationException)
|
||||
{
|
||||
// Self referencing loop detected for property 'Parent' with type
|
||||
// 'Newtonsoft.Json.Tests.Documentation.Examples.ReferenceLoopHandlingObject+Directory'. Path 'Files[0]'.
|
||||
}
|
||||
|
||||
string preserveReferenacesAll = JsonConvert.SerializeObject(documents, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
PreserveReferencesHandling = PreserveReferencesHandling.All
|
||||
});
|
||||
|
||||
Console.WriteLine(preserveReferenacesAll);
|
||||
// {
|
||||
// "$id": "1",
|
||||
// "Name": "My Documents",
|
||||
// "Parent": {
|
||||
// "$id": "2",
|
||||
// "Name": "Root",
|
||||
// "Parent": null,
|
||||
// "Files": null
|
||||
// },
|
||||
// "Files": {
|
||||
// "$id": "3",
|
||||
// "$values": [
|
||||
// {
|
||||
// "$id": "4",
|
||||
// "Name": "ImportantLegalDocument.docx",
|
||||
// "Parent": {
|
||||
// "$ref": "1"
|
||||
// }
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// }
|
||||
|
||||
string preserveReferenacesObjects = JsonConvert.SerializeObject(documents, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
PreserveReferencesHandling = PreserveReferencesHandling.Objects
|
||||
});
|
||||
|
||||
Console.WriteLine(preserveReferenacesObjects);
|
||||
// {
|
||||
// "$id": "1",
|
||||
// "Name": "My Documents",
|
||||
// "Parent": {
|
||||
// "$id": "2",
|
||||
// "Name": "Root",
|
||||
// "Parent": null,
|
||||
// "Files": null
|
||||
// },
|
||||
// "Files": [
|
||||
// {
|
||||
// "$id": "3",
|
||||
// "Name": "ImportantLegalDocument.docx",
|
||||
// "Parent": {
|
||||
// "$ref": "1"
|
||||
// }
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class PropertyJsonIgnore
|
||||
{
|
||||
#region Types
|
||||
public class Account
|
||||
{
|
||||
public string FullName { get; set; }
|
||||
public string EmailAddress { get; set; }
|
||||
[JsonIgnore]
|
||||
public string PasswordHash { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Account account = new Account
|
||||
{
|
||||
FullName = "Joe User",
|
||||
EmailAddress = "joe@example.com",
|
||||
PasswordHash = "VHdlZXQgJ1F1aWNrc2lsdmVyJyB0byBASmFtZXNOSw=="
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(account);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {"FullName":"Joe User","EmailAddress":"joe@example.com"}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class ReferenceLoopHandlingIgnore
|
||||
{
|
||||
#region Types
|
||||
public class Employee
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public Employee Manager { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Employee joe = new Employee { Name = "Joe User" };
|
||||
Employee mike = new Employee { Name = "Mike Manager" };
|
||||
joe.Manager = mike;
|
||||
mike.Manager = mike;
|
||||
|
||||
string json = JsonConvert.SerializeObject(joe, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
|
||||
});
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "Name": "Joe User",
|
||||
// "Manager": {
|
||||
// "Name": "Mike Manager"
|
||||
// }
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializationCallbackAttributes
|
||||
{
|
||||
#region Types
|
||||
public class SerializationEventTestObject
|
||||
{
|
||||
// 2222
|
||||
// This member is serialized and deserialized with no change.
|
||||
public int Member1 { get; set; }
|
||||
|
||||
// The value of this field is set and reset during and
|
||||
// after serialization.
|
||||
public string Member2 { get; set; }
|
||||
|
||||
// This field is not serialized. The OnDeserializedAttribute
|
||||
// is used to set the member value after serialization.
|
||||
[JsonIgnore]
|
||||
public string Member3 { get; set; }
|
||||
|
||||
// This field is set to null, but populated after deserialization.
|
||||
public string Member4 { get; set; }
|
||||
|
||||
public SerializationEventTestObject()
|
||||
{
|
||||
Member1 = 11;
|
||||
Member2 = "Hello World!";
|
||||
Member3 = "This is a nonserialized value";
|
||||
Member4 = null;
|
||||
}
|
||||
|
||||
[OnSerializing]
|
||||
internal void OnSerializingMethod(StreamingContext context)
|
||||
{
|
||||
Member2 = "This value went into the data file during serialization.";
|
||||
}
|
||||
|
||||
[OnSerialized]
|
||||
internal void OnSerializedMethod(StreamingContext context)
|
||||
{
|
||||
Member2 = "This value was reset after serialization.";
|
||||
}
|
||||
|
||||
[OnDeserializing]
|
||||
internal void OnDeserializingMethod(StreamingContext context)
|
||||
{
|
||||
Member3 = "This value was set during deserialization";
|
||||
}
|
||||
|
||||
[OnDeserialized]
|
||||
internal void OnDeserializedMethod(StreamingContext context)
|
||||
{
|
||||
Member4 = "This value was set after deserialization.";
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
SerializationEventTestObject obj = new SerializationEventTestObject();
|
||||
|
||||
Console.WriteLine(obj.Member1);
|
||||
// 11
|
||||
Console.WriteLine(obj.Member2);
|
||||
// Hello World!
|
||||
Console.WriteLine(obj.Member3);
|
||||
// This is a nonserialized value
|
||||
Console.WriteLine(obj.Member4);
|
||||
// null
|
||||
|
||||
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
|
||||
// {
|
||||
// "Member1": 11,
|
||||
// "Member2": "This value went into the data file during serialization.",
|
||||
// "Member4": null
|
||||
// }
|
||||
|
||||
Console.WriteLine(obj.Member1);
|
||||
// 11
|
||||
Console.WriteLine(obj.Member2);
|
||||
// This value was reset after serialization.
|
||||
Console.WriteLine(obj.Member3);
|
||||
// This is a nonserialized value
|
||||
Console.WriteLine(obj.Member4);
|
||||
// null
|
||||
|
||||
obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);
|
||||
|
||||
Console.WriteLine(obj.Member1);
|
||||
// 11
|
||||
Console.WriteLine(obj.Member2);
|
||||
// This value went into the data file during serialization.
|
||||
Console.WriteLine(obj.Member3);
|
||||
// This value was set during deserialization
|
||||
Console.WriteLine(obj.Member4);
|
||||
// This value was set after deserialization.
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeCollection
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
List<string> videogames = new List<string>
|
||||
{
|
||||
"Starcraft",
|
||||
"Halo",
|
||||
"Legend of Zelda"
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(videogames);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// ["Starcraft","Halo","Legend of Zelda"]
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeConditionalProperty
|
||||
{
|
||||
#region Types
|
||||
public class Employee
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public Employee Manager { get; set; }
|
||||
|
||||
public bool ShouldSerializeManager()
|
||||
{
|
||||
// don't serialize the Manager property if an employee is their own manager
|
||||
return (Manager != this);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Employee joe = new Employee();
|
||||
joe.Name = "Joe Employee";
|
||||
Employee mike = new Employee();
|
||||
mike.Name = "Mike Manager";
|
||||
|
||||
joe.Manager = mike;
|
||||
|
||||
// mike is his own manager
|
||||
// ShouldSerialize will skip this property
|
||||
mike.Manager = mike;
|
||||
|
||||
string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// [
|
||||
// {
|
||||
// "Name": "Joe Employee",
|
||||
// "Manager": {
|
||||
// "Name": "Mike Manager"
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// "Name": "Mike Manager"
|
||||
// }
|
||||
// ]
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeContractResolver
|
||||
{
|
||||
#region Types
|
||||
public class Person
|
||||
{
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
|
||||
public string FullName
|
||||
{
|
||||
get { return FirstName + " " + LastName; }
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Person person = new Person
|
||||
{
|
||||
FirstName = "Sarah",
|
||||
LastName = "Security"
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
||||
});
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "firstName": "Sarah",
|
||||
// "lastName": "Security",
|
||||
// "fullName": "Sarah Security"
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeDataSet
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
DataSet dataSet = new DataSet("dataSet");
|
||||
dataSet.Namespace = "NetFrameWork";
|
||||
DataTable table = new DataTable();
|
||||
DataColumn idColumn = new DataColumn("id", typeof(int));
|
||||
idColumn.AutoIncrement = true;
|
||||
|
||||
DataColumn itemColumn = new DataColumn("item");
|
||||
table.Columns.Add(idColumn);
|
||||
table.Columns.Add(itemColumn);
|
||||
dataSet.Tables.Add(table);
|
||||
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
DataRow newRow = table.NewRow();
|
||||
newRow["item"] = "item " + i;
|
||||
table.Rows.Add(newRow);
|
||||
}
|
||||
|
||||
dataSet.AcceptChanges();
|
||||
|
||||
string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "Table1": [
|
||||
// {
|
||||
// "id": 0,
|
||||
// "item": "item 0"
|
||||
// },
|
||||
// {
|
||||
// "id": 1,
|
||||
// "item": "item 1"
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeDateFormatHandling
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
DateTime mayanEndOfTheWorld = new DateTime(2012, 12, 21);
|
||||
|
||||
string jsonIsoDate = JsonConvert.SerializeObject(mayanEndOfTheWorld);
|
||||
|
||||
Console.WriteLine(jsonIsoDate);
|
||||
// "2012-12-21T00:00:00"
|
||||
|
||||
string jsonMsDate = JsonConvert.SerializeObject(mayanEndOfTheWorld, new JsonSerializerSettings
|
||||
{
|
||||
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonMsDate);
|
||||
// "\/Date(1356044400000+0100)\/"
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeDateTimeZoneHandling
|
||||
{
|
||||
#region Types
|
||||
public class Flight
|
||||
{
|
||||
public string Destination { get; set; }
|
||||
public DateTime DepartureDate { get; set; }
|
||||
public DateTime DepartureDateUtc { get; set; }
|
||||
public DateTime DepartureDateLocal { get; set; }
|
||||
public TimeSpan Duration { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Flight flight = new Flight
|
||||
{
|
||||
Destination = "Dubai",
|
||||
DepartureDate = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Unspecified),
|
||||
DepartureDateUtc = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Utc),
|
||||
DepartureDateLocal = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Local),
|
||||
Duration = TimeSpan.FromHours(5.5)
|
||||
};
|
||||
|
||||
string jsonWithRoundtripTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonWithRoundtripTimeZone);
|
||||
// {
|
||||
// "Destination": "Dubai",
|
||||
// "DepartureDate": "2013-01-21T00:00:00",
|
||||
// "DepartureDateUtc": "2013-01-21T00:00:00Z",
|
||||
// "DepartureDateLocal": "2013-01-21T00:00:00+01:00",
|
||||
// "Duration": "05:30:00"
|
||||
// }
|
||||
|
||||
string jsonWithLocalTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
DateTimeZoneHandling = DateTimeZoneHandling.Local
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonWithLocalTimeZone);
|
||||
// {
|
||||
// "Destination": "Dubai",
|
||||
// "DepartureDate": "2013-01-21T00:00:00+01:00",
|
||||
// "DepartureDateUtc": "2013-01-21T01:00:00+01:00",
|
||||
// "DepartureDateLocal": "2013-01-21T00:00:00+01:00",
|
||||
// "Duration": "05:30:00"
|
||||
// }
|
||||
|
||||
string jsonWithUtcTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
DateTimeZoneHandling = DateTimeZoneHandling.Utc
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonWithUtcTimeZone);
|
||||
// {
|
||||
// "Destination": "Dubai",
|
||||
// "DepartureDate": "2013-01-21T00:00:00Z",
|
||||
// "DepartureDateUtc": "2013-01-21T00:00:00Z",
|
||||
// "DepartureDateLocal": "2013-01-20T23:00:00Z",
|
||||
// "Duration": "05:30:00"
|
||||
// }
|
||||
|
||||
string jsonWithUnspecifiedTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonWithUnspecifiedTimeZone);
|
||||
// {
|
||||
// "Destination": "Dubai",
|
||||
// "DepartureDate": "2013-01-21T00:00:00",
|
||||
// "DepartureDateUtc": "2013-01-21T00:00:00",
|
||||
// "DepartureDateLocal": "2013-01-21T00:00:00",
|
||||
// "Duration": "05:30:00"
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeDictionary
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Dictionary<string, int> points = new Dictionary<string, int>
|
||||
{
|
||||
{ "James", 9001 },
|
||||
{ "Jo", 3474 },
|
||||
{ "Jess", 11926 }
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(points, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "James": 9001,
|
||||
// "Jo": 3474,
|
||||
// "Jess": 11926
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeObject
|
||||
{
|
||||
#region Types
|
||||
public class Account
|
||||
{
|
||||
public string Email { get; set; }
|
||||
public bool Active { get; set; }
|
||||
public DateTime CreatedDate { get; set; }
|
||||
public IList<string> Roles { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Account account = new Account
|
||||
{
|
||||
Email = "james@example.com",
|
||||
Active = true,
|
||||
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
|
||||
Roles = new List<string>
|
||||
{
|
||||
"User",
|
||||
"Admin"
|
||||
}
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
|
||||
// {
|
||||
// "Email": "james@example.com",
|
||||
// "Active": true,
|
||||
// "CreatedDate": "2013-01-20T00:00:00Z",
|
||||
// "Roles": [
|
||||
// "User",
|
||||
// "Admin"
|
||||
// ]
|
||||
// }
|
||||
|
||||
Console.WriteLine(json);
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeRawJson
|
||||
{
|
||||
#region Types
|
||||
public class JavaScriptSettings
|
||||
{
|
||||
public JRaw OnLoadFunction { get; set; }
|
||||
public JRaw OnUnloadFunction { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
JavaScriptSettings settings = new JavaScriptSettings
|
||||
{
|
||||
OnLoadFunction = new JRaw("OnLoad"),
|
||||
OnUnloadFunction = new JRaw("function(e) { alert(e); }")
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(settings, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "OnLoadFunction": OnLoad,
|
||||
// "OnUnloadFunction": function(e) { alert(e); }
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeSerializationBinder
|
||||
{
|
||||
#region Types
|
||||
public class KnownTypesBinder : SerializationBinder
|
||||
{
|
||||
public IList<Type> KnownTypes { get; set; }
|
||||
|
||||
public override Type BindToType(string assemblyName, string typeName)
|
||||
{
|
||||
return KnownTypes.SingleOrDefault(t => t.Name == typeName);
|
||||
}
|
||||
|
||||
public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
|
||||
{
|
||||
assemblyName = null;
|
||||
typeName = serializedType.Name;
|
||||
}
|
||||
}
|
||||
|
||||
public class Car
|
||||
{
|
||||
public string Maker { get; set; }
|
||||
public string Model { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
KnownTypesBinder knownTypesBinder = new KnownTypesBinder
|
||||
{
|
||||
KnownTypes = new List<Type> {typeof (Car)}
|
||||
};
|
||||
|
||||
Car car = new Car
|
||||
{
|
||||
Maker = "Ford",
|
||||
Model = "Explorer"
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(car, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.Objects,
|
||||
Binder = knownTypesBinder
|
||||
});
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "$type": "Car",
|
||||
// "Maker": "Ford",
|
||||
// "Model": "Explorer"
|
||||
// }
|
||||
|
||||
object newValue = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.Objects,
|
||||
Binder = knownTypesBinder
|
||||
});
|
||||
|
||||
Console.WriteLine(newValue.GetType().Name);
|
||||
// Car
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeTypeNameHandling
|
||||
{
|
||||
#region Types
|
||||
public abstract class Business
|
||||
{
|
||||
public string Name { get; set; }
|
||||
}
|
||||
|
||||
public class Hotel : Business
|
||||
{
|
||||
public int Stars { get; set; }
|
||||
}
|
||||
|
||||
public class Stockholder
|
||||
{
|
||||
public string FullName { get; set; }
|
||||
public IList<Business> Businesses { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Stockholder stockholder = new Stockholder
|
||||
{
|
||||
FullName = "Steve Stockholder",
|
||||
Businesses = new List<Business>
|
||||
{
|
||||
new Hotel
|
||||
{
|
||||
Name = "Hudson Hotel",
|
||||
Stars = 4
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
string jsonTypeNameAll = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.All
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonTypeNameAll);
|
||||
// {
|
||||
// "$type": "Newtonsoft.Json.Samples.Stockholder, Newtonsoft.Json.Tests",
|
||||
// "FullName": "Steve Stockholder",
|
||||
// "Businesses": {
|
||||
// "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Samples.Business, Newtonsoft.Json.Tests]], mscorlib",
|
||||
// "$values": [
|
||||
// {
|
||||
// "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",
|
||||
// "Stars": 4,
|
||||
// "Name": "Hudson Hotel"
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// }
|
||||
|
||||
string jsonTypeNameAuto = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.Auto
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonTypeNameAuto);
|
||||
// {
|
||||
// "FullName": "Steve Stockholder",
|
||||
// "Businesses": [
|
||||
// {
|
||||
// "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",
|
||||
// "Stars": 4,
|
||||
// "Name": "Hudson Hotel"
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
|
||||
// for security TypeNameHandling is required when deserializing
|
||||
Stockholder newStockholder = JsonConvert.DeserializeObject<Stockholder>(jsonTypeNameAuto, new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.Auto
|
||||
});
|
||||
|
||||
Console.WriteLine(newStockholder.Businesses[0].GetType().Name);
|
||||
// Hotel
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeUnindentedJson
|
||||
{
|
||||
#region Types
|
||||
public class Account
|
||||
{
|
||||
public string Email { get; set; }
|
||||
public bool Active { get; set; }
|
||||
public DateTime CreatedDate { get; set; }
|
||||
public IList<string> Roles { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Account account = new Account
|
||||
{
|
||||
Email = "james@example.com",
|
||||
Active = true,
|
||||
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
|
||||
Roles = new List<string>
|
||||
{
|
||||
"User",
|
||||
"Admin"
|
||||
}
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(account);
|
||||
// {"Email":"james@example.com","Active":true,"CreatedDate":"2013-01-20T00:00:00Z","Roles":["User","Admin"]}
|
||||
|
||||
Console.WriteLine(json);
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeWithJsonConverters
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
List<StringComparison> stringComparisons = new List<StringComparison>
|
||||
{
|
||||
StringComparison.CurrentCulture,
|
||||
StringComparison.InvariantCulture
|
||||
};
|
||||
|
||||
string jsonWithoutConverter = JsonConvert.SerializeObject(stringComparisons);
|
||||
|
||||
Console.WriteLine(jsonWithoutConverter);
|
||||
// [0,2]
|
||||
|
||||
string jsonWithConverter = JsonConvert.SerializeObject(stringComparisons, new StringEnumConverter());
|
||||
|
||||
Console.WriteLine(jsonWithConverter);
|
||||
// ["CurrentCulture","InvariantCulture"]
|
||||
|
||||
List<StringComparison> newStringComparsions = JsonConvert.DeserializeObject<List<StringComparison>>(
|
||||
jsonWithConverter,
|
||||
new StringEnumConverter());
|
||||
|
||||
Console.WriteLine(string.Join(", ", newStringComparsions.Select(c => c.ToString())));
|
||||
// CurrentCulture, InvariantCulture
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using File = System.IO.File;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class SerializeWithJsonSerializerToFile
|
||||
{
|
||||
#region Types
|
||||
public class Movie
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public int Year { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
Movie movie = new Movie
|
||||
{
|
||||
Name = "Bad Boys",
|
||||
Year = 1995
|
||||
};
|
||||
|
||||
// serialize JSON to a string and then write string to a file
|
||||
File.WriteAllText(@"c:\movie.json", JsonConvert.SerializeObject(movie));
|
||||
|
||||
// serialize JSON directly to a file
|
||||
using (StreamWriter file = File.CreateText(@"c:\movie.json"))
|
||||
{
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
serializer.Serialize(file, movie);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
|
||||
{
|
||||
public class TraceWriter
|
||||
{
|
||||
#region Types
|
||||
public class Account
|
||||
{
|
||||
public string FullName { get; set; }
|
||||
public bool Deleted { get; set; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'FullName': 'Dan Deleted',
|
||||
'Deleted': true,
|
||||
'DeletedDate': '2013-01-20T00:00:00'
|
||||
}";
|
||||
|
||||
MemoryTraceWriter traceWriter = new MemoryTraceWriter();
|
||||
|
||||
Account account = JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings
|
||||
{
|
||||
TraceWriter = traceWriter
|
||||
});
|
||||
|
||||
Console.WriteLine(traceWriter.ToString());
|
||||
// 2013-01-21T01:36:24.422 Info Started deserializing Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path 'FullName', line 2, position 20.
|
||||
// 2013-01-21T01:36:24.442 Verbose Could not find member 'DeletedDate' on Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path 'DeletedDate', line 4, position 23.
|
||||
// 2013-01-21T01:36:24.447 Info Finished deserializing Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path '', line 5, position 8.
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Xml
|
||||
{
|
||||
public class ConvertJsonToXml
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string json = @"{
|
||||
'@Id': 1,
|
||||
'Email': 'james@example.com',
|
||||
'Active': true,
|
||||
'CreatedDate': '2013-01-20T00:00:00Z',
|
||||
'Roles': [
|
||||
'User',
|
||||
'Admin'
|
||||
],
|
||||
'Team': {
|
||||
'@Id': 2,
|
||||
'Name': 'Software Developers',
|
||||
'Description': 'Creators of fine software products and services.'
|
||||
}
|
||||
}";
|
||||
|
||||
XNode node = JsonConvert.DeserializeXNode(json, "Root");
|
||||
|
||||
Console.WriteLine(node.ToString());
|
||||
// <Root Id="1">
|
||||
// <Email>james@example.com</Email>
|
||||
// <Active>true</Active>
|
||||
// <CreatedDate>2013-01-20T00:00:00Z</CreatedDate>
|
||||
// <Roles>User</Roles>
|
||||
// <Roles>Admin</Roles>
|
||||
// <Team Id="2">
|
||||
// <Name>Software Developers</Name>
|
||||
// <Description>Creators of fine software products and services.</Description>
|
||||
// </Team>
|
||||
// </Root>
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Xml
|
||||
{
|
||||
public class ConvertXmlToJson
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string xml = @"<?xml version='1.0' standalone='no'?>
|
||||
<root>
|
||||
<person id='1'>
|
||||
<name>Alan</name>
|
||||
<url>http://www.google.com</url>
|
||||
</person>
|
||||
<person id='2'>
|
||||
<name>Louis</name>
|
||||
<url>http://www.yahoo.com</url>
|
||||
</person>
|
||||
</root>";
|
||||
|
||||
XmlDocument doc = new XmlDocument();
|
||||
doc.LoadXml(xml);
|
||||
|
||||
string json = JsonConvert.SerializeXmlNode(doc);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "?xml": {
|
||||
// "@version": "1.0",
|
||||
// "@standalone": "no"
|
||||
// },
|
||||
// "root": {
|
||||
// "person": [
|
||||
// {
|
||||
// "@id": "1",
|
||||
// "name": "Alan",
|
||||
// "url": "http://www.google.com"
|
||||
// },
|
||||
// {
|
||||
// "@id": "2",
|
||||
// "name": "Louis",
|
||||
// "url": "http://www.yahoo.com"
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Samples.Xml
|
||||
{
|
||||
public class ConvertXmlToJsonForceArray
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
#region Usage
|
||||
string xml = @"<person id='1'>
|
||||
<name>Alan</name>
|
||||
<url>http://www.google.com</url>
|
||||
<role>Admin1</role>
|
||||
</person>";
|
||||
|
||||
XmlDocument doc = new XmlDocument();
|
||||
doc.LoadXml(xml);
|
||||
|
||||
string json = JsonConvert.SerializeXmlNode(doc);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "person": {
|
||||
// "@id": "1",
|
||||
// "name": "Alan",
|
||||
// "url": "http://www.google.com",
|
||||
// "role": "Admin1"
|
||||
// }
|
||||
// }
|
||||
|
||||
xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
|
||||
<name>Alan</name>
|
||||
<url>http://www.google.com</url>
|
||||
<role json:Array='true'>Admin</role>
|
||||
</person>";
|
||||
|
||||
doc = new XmlDocument();
|
||||
doc.LoadXml(xml);
|
||||
|
||||
json = JsonConvert.SerializeXmlNode(doc);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "person": {
|
||||
// "@id": "1",
|
||||
// "name": "Alan",
|
||||
// "url": "http://www.google.com",
|
||||
// "role": [
|
||||
// "Admin"
|
||||
// ]
|
||||
// }
|
||||
// }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user