-Samples!

This commit is contained in:
James Newton-King
2013-01-28 23:20:05 +13:00
parent 849f7a9fa8
commit 1c0e2856c2
208 changed files with 713 additions and 693 deletions
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}