-Reorganized examples
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class CustomContractResolver
|
||||
{
|
||||
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; }
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class CustomJsonConverter
|
||||
{
|
||||
public class KeysJsonConverter : JsonConverter
|
||||
{
|
||||
private 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("This is not necessary because CanRead is false so the type will be deserialized as normal.");
|
||||
}
|
||||
|
||||
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; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class CustomTraceWriter
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// ]
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DataContractAndDataMember
|
||||
{
|
||||
[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; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DefaultValueAttributeIgnore
|
||||
{
|
||||
public class Customer
|
||||
{
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
|
||||
[DefaultValue(" ")]
|
||||
public string FullName
|
||||
{
|
||||
get { return FirstName + " " + LastName; }
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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);
|
||||
// {}
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DefaultValueHandlingIgnore
|
||||
{
|
||||
public class Person
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public int Age { get; set; }
|
||||
public Person Partner { get; set; }
|
||||
public decimal? Salary { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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);
|
||||
// {}
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DeserializeAnonymousType
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
string json = @"{""Name"":""James""}";
|
||||
|
||||
var customerDefinition = new {Name = ""};
|
||||
|
||||
var customer = JsonConvert.DeserializeAnonymousType(json, customerDefinition);
|
||||
|
||||
Console.WriteLine(customer.Name);
|
||||
// James
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DeserializeCollection
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DeserializeConstructorHandling
|
||||
{
|
||||
public class Website
|
||||
{
|
||||
public string Url { get; set; }
|
||||
|
||||
private Website()
|
||||
{
|
||||
}
|
||||
|
||||
public Website(Website website)
|
||||
{
|
||||
if (website == null)
|
||||
throw new ArgumentNullException("website");
|
||||
|
||||
Url = website.Url;
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
string json = @"{""Url"":""http://www.google.com""}";
|
||||
|
||||
try
|
||||
{
|
||||
JsonConvert.DeserializeObject<Website>(json);
|
||||
}
|
||||
catch (TargetInvocationException)
|
||||
{
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DeserializeCustomCreationConverter
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DeserializeDataSet
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DeserializeDictionary
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DeserializeMissingMemberHandling
|
||||
{
|
||||
public class Account
|
||||
{
|
||||
public string FullName { get; set; }
|
||||
public bool Deleted { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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)
|
||||
{
|
||||
// Could not find member 'DeletedDate' on object of type 'Account'. Path 'DeletedDate', line 4, position 23.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DeserializeObject
|
||||
{
|
||||
public class Account
|
||||
{
|
||||
public string Email { get; set; }
|
||||
public bool Active { get; set; }
|
||||
public DateTime CreatedDate { get; set; }
|
||||
public IList<string> Roles { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class DeserializeObjectCreationHandling
|
||||
{
|
||||
public class UserViewModel
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public IList<string> Offices { get; private set; }
|
||||
|
||||
public UserViewModel()
|
||||
{
|
||||
Offices = new List<string>
|
||||
{
|
||||
"Auckland",
|
||||
"Wellington",
|
||||
"Christchurch"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
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.Examples
|
||||
{
|
||||
public class DeserializeWithJsonSerializerFromFile
|
||||
{
|
||||
public class Movie
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public int Year { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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.Examples
|
||||
{
|
||||
public class ErrorHandlingAttribute
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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.Examples
|
||||
{
|
||||
public class ErrorHandlingEvent
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
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.
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class JsonConverterAttributeClass
|
||||
{
|
||||
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; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
User user = new User
|
||||
{
|
||||
UserName = @"domain\username"
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(user, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// "domain\\username"
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class JsonConverterAttributeProperty
|
||||
{
|
||||
public enum UserStatus
|
||||
{
|
||||
NotConfirmed,
|
||||
Active,
|
||||
Deleted
|
||||
}
|
||||
|
||||
public class User
|
||||
{
|
||||
public string UserName { get; set; }
|
||||
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
public UserStatus Status { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class JsonObjectAttributeOptIn
|
||||
{
|
||||
[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; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class JsonObjectAttributeOverrideIEnumerable
|
||||
{
|
||||
[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();
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// ]
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class JsonPropertyItemLevelSetting
|
||||
{
|
||||
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; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class JsonPropertyName
|
||||
{
|
||||
public class Videogame
|
||||
{
|
||||
[JsonProperty("name")]
|
||||
public string Name { get; set; }
|
||||
|
||||
[JsonProperty("release_date")]
|
||||
public DateTime ReleaseDate { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class JsonPropertyOrder
|
||||
{
|
||||
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; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class JsonPropertyPropertyLevelSetting
|
||||
{
|
||||
public class Vessel
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string Class { get; set; }
|
||||
|
||||
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
|
||||
public DateTime? LaunchDate { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
Vessel vessel = new Vessel
|
||||
{
|
||||
Name = "Red October",
|
||||
Class = "Typhoon"
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(vessel, Formatting.Indented);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// {
|
||||
// "Name": "Red October",
|
||||
// "Class": "Typhoon"
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class JsonPropertyRequired
|
||||
{
|
||||
public class Videogame
|
||||
{
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Name { get; set; }
|
||||
|
||||
[JsonProperty(Required = Required.AllowNull)]
|
||||
public DateTime? ReleaseDate { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
string json = @"{
|
||||
""Name"": ""Starcraft III"",
|
||||
""ReleaseDate"": null
|
||||
}";
|
||||
|
||||
Videogame starcraft = JsonConvert.DeserializeObject<Videogame>(json);
|
||||
|
||||
Console.WriteLine(starcraft.Name);
|
||||
// Starcraft III
|
||||
|
||||
Console.WriteLine(starcraft.ReleaseDate);
|
||||
// null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class MaxDepth
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
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.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class NullValueHandlingIgnore
|
||||
{
|
||||
public class Person
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public int Age { get; set; }
|
||||
public Person Partner { get; set; }
|
||||
public decimal? Salary { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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 = Json.NullValueHandling.Ignore
|
||||
});
|
||||
|
||||
Console.WriteLine(jsonIgnoreNullValues);
|
||||
// {
|
||||
// "Name": "Nigal Newborn",
|
||||
// "Age": 1
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class PopulateObject
|
||||
{
|
||||
public class Account
|
||||
{
|
||||
public string Email { get; set; }
|
||||
public bool Active { get; set; }
|
||||
public DateTime CreatedDate { get; set; }
|
||||
public IList<string> Roles { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class PropertyJsonIgnore
|
||||
{
|
||||
public class Account
|
||||
{
|
||||
public string FullName { get; set; }
|
||||
public string EmailAddress { get; set; }
|
||||
[JsonIgnore]
|
||||
public string PasswordHash { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"}
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class ReferenceLoopHandlingIgnore
|
||||
{
|
||||
public class Employee
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public Employee Manager { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class ReferenceLoopHandlingObject
|
||||
{
|
||||
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; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializationCallbackAttributes
|
||||
{
|
||||
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.";
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeCollection
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
List<string> videogames = new List<string>
|
||||
{
|
||||
"Starcraft",
|
||||
"Halo",
|
||||
"Legend of Zelda"
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(videogames);
|
||||
|
||||
Console.WriteLine(json);
|
||||
// ["Starcraft","Halo","Legend of Zelda"]
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeConditionalProperty
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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);
|
||||
// [
|
||||
// {
|
||||
// "Name": "Joe Employee",
|
||||
// "Manager": {
|
||||
// "Name": "Mike Manager"
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// "Name": "Mike Manager"
|
||||
// }
|
||||
// ]
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeContractResolver
|
||||
{
|
||||
public class Person
|
||||
{
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
|
||||
public string FullName
|
||||
{
|
||||
get { return FirstName + " " + LastName; }
|
||||
}
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeDataSet
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeDateFormatHandling
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
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)\/"
|
||||
}
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeDateTimeZoneHandling
|
||||
{
|
||||
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; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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"
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeDictionary
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeObject
|
||||
{
|
||||
public class Account
|
||||
{
|
||||
public string Email { get; set; }
|
||||
public bool Active { get; set; }
|
||||
public DateTime CreatedDate { get; set; }
|
||||
public IList<string> Roles { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeRawJson
|
||||
{
|
||||
public class JavaScriptSettings
|
||||
{
|
||||
public JRaw OnLoadFunction { get; set; }
|
||||
public JRaw OnUnloadFunction { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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); }
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeSerializationBinder
|
||||
{
|
||||
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; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeTypeNameHandling
|
||||
{
|
||||
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; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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.Tests.Documentation.Examples.SerializeTypeNameHandling+Stockholder, Newtonsoft.Json.Tests",
|
||||
// "FullName": "Steve Stockholder",
|
||||
// "Businesses": {
|
||||
// "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Tests.Documentation.Examples.SerializeTypeNameHandling+Business, Newtonsoft.Json.Tests]], mscorlib",
|
||||
// "$values": [
|
||||
// {
|
||||
// "$type": "Newtonsoft.Json.Tests.Documentation.Examples.SerializeTypeNameHandling+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.Tests.Documentation.Examples.SerializeTypeNameHandling+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
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeUnindentedJson
|
||||
{
|
||||
public class Account
|
||||
{
|
||||
public string Email { get; set; }
|
||||
public bool Active { get; set; }
|
||||
public DateTime CreatedDate { get; set; }
|
||||
public IList<string> Roles { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class SerializeWithJsonConverters
|
||||
{
|
||||
public void Example()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
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.Examples
|
||||
{
|
||||
public class SerializeWithJsonSerializerToFile
|
||||
{
|
||||
public class Movie
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public int Year { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace Newtonsoft.Json.Tests.Documentation.Examples
|
||||
{
|
||||
public class TraceWriter
|
||||
{
|
||||
public class Account
|
||||
{
|
||||
public string FullName { get; set; }
|
||||
public bool Deleted { get; set; }
|
||||
}
|
||||
|
||||
public void Example()
|
||||
{
|
||||
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.
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user