-JSON Schema fixes

-Fixed static values being included with fields serialization
-Examples! (work in progress)
This commit is contained in:
James Newton-King
2013-01-23 21:39:54 +13:00
parent 9187d8a6b3
commit 68eacc480b
87 changed files with 3519 additions and 53 deletions
+1 -1
View File
@@ -58,7 +58,7 @@
<linkText>conditional serialization for a property</linkText>
<linkUri>ConditionalProperties.htm</linkUri>
<linkTarget>_self</linkTarget>
</externalLink> using an IContractResolver. This is useful if you want to conditional serialize a property but don't want to add additional methods to your type.</para>
</externalLink> using an IContractResolver. This is useful if you want to conditionally serialize a property but don't want to add additional methods to your type.</para>
</content>
</section>
<relatedTopics>
@@ -216,7 +216,7 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual("shoes", table.Rows[2]["item"]);
Assert.AreEqual(49.99, (double)table.Rows[0]["price"], 0.01);
Assert.AreEqual(54.99, (double)table.Rows[1]["price"], 0.01);
Assert.IsInstanceOfType(typeof(System.DBNull), table.Rows[2]["price"]);
CustomAssert.IsInstanceOfType(typeof(System.DBNull), table.Rows[2]["price"]);
}
[Test]
@@ -232,7 +232,7 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual("shoes", table.Rows[2]["item"]);
Assert.AreEqual(49.99, (double)table.Rows[0]["price"], 0.01);
Assert.AreEqual(54.99, (double)table.Rows[1]["price"], 0.01);
Assert.IsInstanceOfType(typeof(System.DBNull), table.Rows[2]["price"]);
CustomAssert.IsInstanceOfType(typeof(System.DBNull), table.Rows[2]["price"]);
}
[Test]
@@ -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,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
// }
}
}
}
@@ -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);
// {}
}
}
}
@@ -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);
// {}
}
}
}
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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,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
}
}
}
@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Bson;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class DeserializeFromBson
{
public class Event
{
public string Name { get; set; }
public DateTime StartDate { get; set; }
}
public void Example()
{
byte[] data = Convert.FromBase64String("MAAAAAJOYW1lAA4AAABNb3ZpZSBwcmVtaWVyAAlTdGFydERhdGUAwOApYTwBAAAA");
MemoryStream ms = new MemoryStream(data);
using (BsonReader reader = new BsonReader(ms))
{
JsonSerializer serializer = new JsonSerializer();
Event e = serializer.Deserialize<Event>(reader);
Console.WriteLine(e.Name);
// Movie premier
}
}
}
}
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Bson;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class DeserializeFromBsonCollection
{
public class Event
{
public string Name { get; set; }
public DateTime StartDate { get; set; }
}
public void Example()
{
byte[] data = Convert.FromBase64String("awAAAAMwADAAAAACTmFtZQAOAAAATW92aWUgcHJlbWllcgAJU3RhcnREYXRlAMDgKWE8AQAAAAMxADAAAAACTmFtZQAOAAAATW92aWUgcHJlbWllcgAJU3RhcnREYXRlAMDgKWE8AQAAAAA=");
MemoryStream ms = new MemoryStream(data);
using (BsonReader reader = new BsonReader(ms))
{
reader.ReadRootValueAsArray = true;
JsonSerializer serializer = new JsonSerializer();
IList<Event> events = serializer.Deserialize<IList<Event>>(reader);
Console.WriteLine(events.Count);
// 2
}
}
}
}
@@ -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
}
}
}
@@ -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 DeserializeWithJsonSerializerToFile
{
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,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.
}
}
}
@@ -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"
}
}
}
@@ -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"
// }
}
}
}
@@ -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
// }
}
}
}
@@ -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 = "Mabae",
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": "Mabae",
// "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"
// }
}
}
}
@@ -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,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class Clone
{
public void Example()
{
JObject o1 = new JObject
{
{"String", "A string!"},
{"Items", new JArray(1, 2)}
};
Console.WriteLine(o1.ToString());
// {
// "String": "A string!",
// "Items": [
// 1,
// 2
// ]
// }
JObject o2 = (JObject) o1.DeepClone();
Console.WriteLine(o2.ToString());
// {
// "String": "A string!",
// "Items": [
// 1,
// 2
// ]
// }
Console.WriteLine(JToken.DeepEquals(o1, o2));
// true
Console.WriteLine(Object.ReferenceEquals(o1, o2));
// false
}
}
}
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class CreateJsonAnonymousObject
{
public class Post
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public IList<string> Categories { get; set; }
}
public void Example()
{
List<Post> posts = new List<Post>
{
new Post
{
Title = "Episode VII",
Description = "Episode VII production",
Categories = new List<string>
{
"episode-vii",
"movie"
},
Link = "episode-vii-production.aspx"
}
};
JObject o = JObject.FromObject(new
{
channel = new
{
title = "Star Wars",
link = "http://www.starwars.com",
description = "Star Wars blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
Console.WriteLine(o.ToString());
// {
// "channel": {
// "title": "Star Wars",
// "link": "http://www.starwars.com",
// "description": "Star Wars blog.",
// "item": [
// {
// "title": "Episode VII",
// "description": "Episode VII production",
// "link": "episode-vii-production.aspx",
// "category": [
// "episode-vii",
// "movie"
// ]
// }
// ]
// }
// }
}
}
}
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class CreateJsonCollectionInitializer
{
public void Example()
{
JObject o = new JObject
{
{"Cpu", "Intel"},
{"Memory", 32},
{
"Drives", new JArray
{
"DVD",
"SSD"
}
}
};
Console.WriteLine(o.ToString());
// {
// "Cpu": "Intel",
// "Memory": 32,
// "Drives": [
// "DVD",
// "SSD"
// ]
// }
}
}
}
@@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class CreateJsonDeclaratively
{
public class Post
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public IList<string> Categories { get; set; }
}
private List<Post> GetPosts()
{
return null;
}
public void Example()
{
List<Post> posts = GetPosts();
JObject rss =
new JObject(
new JProperty("channel",
new JObject(
new JProperty("title", "James Newton-King"),
new JProperty("link", "http://james.newtonking.com"),
new JProperty("description", "James Newton-King's blog."),
new JProperty("item",
new JArray(
from p in posts
orderby p.Title
select new JObject(
new JProperty("title", p.Title),
new JProperty("description", p.Description),
new JProperty("link", p.Link),
new JProperty("category",
new JArray(
from c in p.Categories
select new JValue(c)))))))));
Console.WriteLine(rss.ToString());
// {
// "channel": {
// "title": "James Newton-King",
// "link": "http://james.newtonking.com",
// "description": "James Newton-King's blog.",
// "item": [
// {
// "title": "Json.NET 1.3 + New license + Now on CodePlex",
// "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
// "link": "http://james.newtonking.com/projects/json-net.aspx",
// "category": [
// "Json.NET",
// "CodePlex"
// ]
// },
// {
// "title": "LINQ to JSON beta",
// "description": "Annoucing LINQ to JSON",
// "link": "http://james.newtonking.com/projects/json-net.aspx",
// "category": [
// "Json.NET",
// "LINQ"
// ]
// }
// ]
// }
// }
}
}
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class CreateJsonDynamic
{
public void Example()
{
dynamic product = new JObject();
product.ProductName = "Elbow Grease";
product.Enabled = true;
product.Price = 4.90m;
product.StockCount = 9000;
product.StockValue = 44100;
product.Tags = new JArray("Real", "OnSale");
Console.WriteLine(product.ToString());
// {
// "ProductName": "Elbow Grease",
// "Enabled": true,
// "Price": 4.90,
// "StockCount": 9000,
// "StockValue": 44100,
// "Tags": [
// "Real",
// "OnSale"
// ]
// }
}
}
}
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class CreateJsonJTokenWriter
{
public void Example()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("name1");
writer.WriteValue("value1");
writer.WritePropertyName("name2");
writer.WriteStartArray();
writer.WriteValue(1);
writer.WriteValue(2);
writer.WriteEndArray();
writer.WriteEndObject();
JObject o = (JObject)writer.Token;
Console.WriteLine(o.ToString());
// {
// "name1": "value1",
// "name2": [
// 1,
// 2
// ]
// }
}
}
}
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class CreateJsonManually
{
public void Example()
{
JArray array = new JArray();
JValue text = new JValue("Manual text");
JValue date = new JValue(new DateTime(2000, 5, 23));
array.Add(text);
array.Add(date);
string json = array.ToString();
Console.WriteLine(json);
// [
// "Manual text",
// "2000-05-23T00:00:00"
// ]
}
}
}
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class CreateReader
{
public void Example()
{
JObject o = new JObject
{
{"Cpu", "Intel"},
{"Memory", 32},
{
"Drives", new JArray
{
"DVD",
"SSD"
}
}
};
JsonReader reader = o.CreateReader();
while (reader.Read())
{
Console.Write(reader.TokenType);
if (reader.Value != null)
Console.Write(" - " + reader.Value);
Console.WriteLine();
}
// StartObject
// PropertyName - Cpu
// String - Intel
// PropertyName - Memory
// Integer - 32
// PropertyName - Drives
// StartArray
// String - DVD
// String - SSD
// EndArray
// EndObject
}
}
}
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class CreateWriter
{
public void Example()
{
JObject o = new JObject
{
{"name1", "value1"},
{"name2", "value2"}
};
JsonWriter writer = o.CreateWriter();
writer.WritePropertyName("name3");
writer.WriteStartArray();
writer.WriteValue(1);
writer.WriteValue(2);
writer.WriteEndArray();
Console.WriteLine(o.ToString());
// {
// "name1": "value1",
// "name2": "value2",
// "name3": [
// 1,
// 2
// ]
// }
}
}
}
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class DeepEquals
{
public void Example()
{
JValue s1 = new JValue("A string");
JValue s2 = new JValue("A string");
JValue s3 = new JValue("A STRING");
Console.WriteLine(JToken.DeepEquals(s1, s2));
// true
Console.WriteLine(JToken.DeepEquals(s2, s3));
// false
JObject o1 = new JObject
{
{"Integer", 12345},
{"String", "A string"},
{"Items", new JArray(1, 2)}
};
JObject o2 = new JObject
{
{"Integer", 12345},
{"String", "A string"},
{"Items", new JArray(1, 2)}
};
Console.WriteLine(JToken.DeepEquals(o1, o2));
// true
Console.WriteLine(JToken.DeepEquals(s1, o1["String"]));
// true
}
}
}
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class DeserializeWithLinq
{
public class BlogPost
{
public string Title { get; set; }
public string AuthorName { get; set; }
public string AuthorTwitter { get; set; }
public string Body { get; set; }
public DateTime PostedDate { get; set; }
}
public void Example()
{
string json = @"[
{
""Title"": ""Json.NET is awesome!"",
""Author"": {
""Name"": ""James Newton-King"",
""Twitter"": ""@JamesNK"",
""Picture"": ""/jamesnk.png""
},
""Date"": ""2013-01-23T19:30:00"",
""BodyHtml"": ""&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;""
}
]";
JArray blogPostArray = JArray.Parse(json);
IList<BlogPost> blogPosts = blogPostArray.Select(p => new BlogPost
{
Title = (string) p["Title"],
AuthorName = (string) p["Author"]["Name"],
AuthorTwitter = (string) p["Author"]["Twitter"],
PostedDate = (DateTime) p["Date"],
Body = HttpUtility.HtmlDecode((string) p["BodyHtml"])
}).ToList();
Console.WriteLine(blogPosts[0].Body);
// <h3>Title!</h3>
// <p>Content!</p>
}
}
}
@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class FromObject
{
public class Computer
{
public string Cpu { get; set; }
public int Memory { get; set; }
public IList<string> Drives { get; set; }
}
public void Example()
{
JValue i = (JValue)JToken.FromObject(12345);
Console.WriteLine(i.Type);
// Integer
Console.WriteLine(i.ToString());
// 12345
JValue s = (JValue)JToken.FromObject("A string");
Console.WriteLine(s.Type);
// String
Console.WriteLine(s.ToString());
// A string
Computer computer = new Computer
{
Cpu = "Intel",
Memory = 32,
Drives = new List<string>
{
"DVD",
"SSD"
}
};
JObject o = (JObject)JToken.FromObject(computer);
Console.WriteLine(o.ToString());
// {
// "Cpu": "Intel",
// "Memory": 32,
// "Drives": [
// "DVD",
// "SSD"
// ]
// }
JArray a = (JArray)JToken.FromObject(computer.Drives);
Console.WriteLine(a.ToString());
// [
// "DVD",
// "SSD"
// ]
}
}
}
@@ -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.Linq
{
public class JObjectProperties
{
public void Example()
{
JObject o = new JObject
{
{ "name1", "value1" },
{ "name2", "value2"}
};
foreach (JProperty property in o.Properties())
{
Console.WriteLine(property.Name + " - " + property.Value);
}
// name1 - value1
// name2 - value2
foreach (KeyValuePair<string, JToken> property in o)
{
Console.WriteLine(property.Key + " - " + property.Value);
}
// name1 - value1
// name2 - value2
}
}
}
@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class JValueCast
{
public void Example()
{
JValue v1 = new JValue("1");
int i = (int)v1;
Console.WriteLine(i);
// 1
JValue v2 = new JValue(true);
bool b = (bool)v2;
Console.WriteLine(b);
// true
JValue v3 = new JValue("19.95");
decimal d = (decimal)v3;
Console.WriteLine(d);
// 19.95
JValue v4 = new JValue(new DateTime(2013, 1, 21));
string s = (string)v4;
Console.WriteLine(s);
// 01/21/2013 00:00:00
JValue v5 = new JValue("http://www.bing.com");
Uri u = (Uri)v5;
Console.WriteLine(u);
// http://www.bing.com/
JValue v6 = new JValue((object)null);
u = (Uri)v6;
Console.WriteLine((u != null) ? u.ToString() : "{null}");
// {null}
DateTime? dt = (DateTime?)v6;
Console.WriteLine((dt != null) ? dt.ToString() : "{null}");
// {null}
}
}
}
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class JValueValue
{
public void Example()
{
JValue s = new JValue("A string value");
Console.WriteLine(s.Value.GetType().Name);
// String
Console.WriteLine(s.Value);
// A string value
JValue u = new JValue(new Uri("http://www.google.com/"));
Console.WriteLine(u.Value.GetType().Name);
// Uri
Console.WriteLine(u.Value);
// http://www.google.com/
}
}
}
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class ModifyJson
{
public void Example()
{
string json = @"{
""channel"": {
""title"": ""Star Wars"",
""link"": ""http://www.starwars.com"",
""description"": ""Star Wars blog."",
""obsolete"": ""Obsolete value"",
""item"": []
}
}";
JObject rss = JObject.Parse(json);
JObject channel = (JObject)rss["channel"];
channel["title"] = ((string)channel["title"]).ToUpper();
channel["description"] = ((string)channel["description"]).ToUpper();
channel.Property("obsolete").Remove();
channel.Property("description").AddAfterSelf(new JProperty("new", "New value"));
JArray item = (JArray) channel["item"];
item.Add("Item 1");
item.Add("Item 2");
Console.WriteLine(rss.ToString());
// {
// "channel": {
// "title": "STAR WARS",
// "link": "http://www.starwars.com",
// "description": "STAR WARS BLOG.",
// "new": "New value",
// "item": [
// "Item 1",
// "Item 2"
// ]
// }
// }
}
}
}
@@ -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.Linq
{
public class ParseJsonAny
{
public void Example()
{
JToken t1 = JToken.Parse("{}");
Console.WriteLine(t1.Type);
// Object
JToken t2 = JToken.Parse("[]");
Console.WriteLine(t2.Type);
// Array
JToken t3 = JToken.Parse("null");
Console.WriteLine(t3.Type);
// Null
JToken t4 = JToken.Parse(@"""A string!""");
Console.WriteLine(t4.Type);
// String
}
}
}
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class ParseJsonArray
{
public void Example()
{
string json = @"[
'Small',
'Medium',
'Large'
]";
JArray a = JArray.Parse(json);
Console.WriteLine(a.ToString());
// [
// "Small",
// "Medium",
// "Large"
// ]
}
}
}
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class ParseJsonObject
{
public void Example()
{
string json = @"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
Console.WriteLine(o.ToString());
// {
// "CPU": "Intel",
// "Drives": [
// "DVD read/writer",
// "500 gigabyte hard drive"
// ]
// }
}
}
}
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class QueryJsonDynamic
{
public void Example()
{
string json = @"[
{
""Title"": ""Json.NET is awesome!"",
""Author"": {
""Name"": ""James Newton-King"",
""Twitter"": ""@JamesNK"",
""Picture"": ""/jamesnk.png""
},
""Date"": ""2013-01-23T19:30:00"",
""BodyHtml"": ""&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;""
}
]";
dynamic blogPosts = JArray.Parse(json);
dynamic blogPost = blogPosts[0];
string title = blogPost.Title;
Console.WriteLine(title);
// Json.NET is awesome!
string author = blogPost.Author.Name;
Console.WriteLine(author);
// James Newton-King
DateTime postDate = blogPost.Date;
Console.WriteLine(postDate);
// 23/01/2013 7:30:00 p.m.
}
}
}
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class ReadJson
{
public void Example()
{
JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject) JToken.ReadFrom(reader);
}
}
}
}
@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class SerializeWithLinq
{
public class BlogPost
{
public string Title { get; set; }
public string AuthorName { get; set; }
public string AuthorTwitter { get; set; }
public string Body { get; set; }
public DateTime PostedDate { get; set; }
}
public void Example()
{
IList<BlogPost> blogPosts = new List<BlogPost>
{
new BlogPost
{
Title = "Json.NET is awesome!",
AuthorName = "James Newton-King",
AuthorTwitter = "JamesNK",
PostedDate = new DateTime(2013, 1, 23, 19, 30, 0),
Body = @"<h3>Title!</h3>
<p>Content!</p>"
}
};
JArray blogPostsArray = new JArray(
blogPosts.Select(p => new JObject
{
{"Title", p.Title},
{
"Author", new JObject
{
{"Name", p.AuthorName},
{"Twitter", p.AuthorTwitter}
}
},
{"Date", p.PostedDate},
{"BodyHtml", HttpUtility.HtmlEncode(p.Body)},
})
);
Console.WriteLine(blogPostsArray.ToString());
// [
// {
// "Title": "Json.NET is awesome!",
// "Author": {
// "Name": "James Newton-King",
// "Twitter": "JamesNK"
// },
// "Date": "2013-01-23T19:30:00",
// "BodyHtml": "&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;"
// }
// ]
}
}
}
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class ToObjectComplex
{
public class Person
{
public string Name { get; set; }
}
public void Example()
{
string json = @"{
""d"": [
{
""Name"": ""John Smith""
},
{
""Name"": ""Mike Smith""
}
]
}";
JObject o = JObject.Parse(json);
JArray a = (JArray)o["d"];
IList<Person> person = a.ToObject<IList<Person>>();
Console.WriteLine(person[0].Name);
// John Smith
Console.WriteLine(person[1].Name);
// Mike Smith
}
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class ToObjectGeneric
{
public void Example()
{
JValue v1 = new JValue(true);
bool b = v1.ToObject<bool>();
Console.WriteLine(b);
// true
int i = v1.ToObject<int>();
Console.WriteLine(i);
// 1
string s = v1.ToObject<string>();
Console.WriteLine(s);
// "True"
}
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class ToObjectType
{
public void Example()
{
JValue v1 = new JValue(true);
bool b = (bool)v1.ToObject(typeof(bool));
Console.WriteLine(b);
// true
int i = (int)v1.ToObject(typeof(int));
Console.WriteLine(i);
// 1
string s = (string)v1.ToObject(typeof(string));
Console.WriteLine(s);
// "True"
}
}
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class ToString
{
public void Example()
{
JObject o = JObject.Parse(@"{'string1':'value','integer2':99,'datetime3':'2000-05-23T00:00:00'}");
Console.WriteLine(o.ToString());
// {
// "string1": "value",
// "integer2": 99,
// "datetime3": "2000-05-23T00:00:00"
// }
Console.WriteLine(o.ToString(Formatting.None));
// {"string1":"value","integer2":99,"datetime3":"2000-05-23T00:00:00"}
Console.WriteLine(o.ToString(Formatting.None, new JavaScriptDateTimeConverter()));
// {"string1":"value","integer2":99,"datetime3":new Date(959032800000)}
}
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class ToStringJsonConverter
{
public void Example()
{
JObject o = JObject.Parse(@"{'string1':'value','integer2':99,'datetime3':'2000-05-23T00:00:00'}");
Console.WriteLine(o.ToString(Formatting.None, new JavaScriptDateTimeConverter()));
// {"string1":"value","integer2":99,"datetime3":new Date(959032800000)}
}
}
}
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class WriteToJsonFile
{
public void Example()
{
JObject videogameRatings = new JObject(
new JProperty("Halo", 9),
new JProperty("Starcraft", 9),
new JProperty("Call of Duty", 7.5));
File.WriteAllText(@"c:\videogames.json", videogameRatings.ToString());
// write JSON directly to a file
using (StreamWriter file = File.CreateText(@"c:\videogames.json"))
using (JsonTextWriter writer = new JsonTextWriter(file))
{
videogameRatings.WriteTo(writer);
}
}
}
}
@@ -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"}
}
}
}
@@ -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"
// }
// }
}
}
}
@@ -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"
// }
// }
// ]
// }
}
}
}
@@ -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"]
}
}
}
@@ -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,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)\/"
}
}
}
@@ -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,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
}
}
}
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class SerializeToBson
{
public class Event
{
public string Name { get; set; }
public DateTime StartDate { get; set; }
}
public void Example()
{
Event e = new Event
{
Name = "Movie premier",
StartDate = new DateTime(2013, 1, 22, 20, 30, 0)
};
IList<Event> es = new List<Event>
{
e, e
};
MemoryStream ms = new MemoryStream();
using (BsonWriter writer = new BsonWriter(ms))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, es);
}
string data = Convert.ToBase64String(ms.ToArray());
Console.WriteLine(data);
// MAAAAAJOYW1lAA4AAABNb3ZpZSBwcmVtaWVyAAlTdGFydERhdGUAwOApYTwBAAAA
}
}
}
@@ -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
}
}
}
@@ -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);
}
}
}
@@ -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
}
}
}
@@ -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.
}
}
}
@@ -56,6 +56,21 @@ namespace Newtonsoft.Json.Tests.Documentation
{
return null;
}
public static StreamWriter CreateText(string path)
{
return null;
}
public static void WriteAllText(string path, string contents)
{
Console.WriteLine(contents);
}
public static string ReadAllText(string path)
{
return null;
}
}
public class LinqToJsonTests
@@ -981,6 +981,11 @@ namespace Newtonsoft.Json.Tests.Linq
t = o.SelectToken("Test3.Test1[1].Test1");
Assert.AreEqual("Test3.Test1[1].Test1", t.Path);
JArray a = new JArray(1);
Assert.AreEqual("", a.Path);
Assert.AreEqual("[0]", a[0].Path);
}
}
}
@@ -54,6 +54,7 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<UseVSHostingProcess>true</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -118,6 +119,76 @@
<Compile Include="Converters\VersionConverterTests.cs" />
<Compile Include="Documentation\ConvertingJsonAndXmlTests.cs" />
<Compile Include="Documentation\ConditionalPropertiesTests.cs" />
<Compile Include="Documentation\Examples\DeserializeFromBson.cs" />
<Compile Include="Documentation\Examples\DeserializeFromBsonCollection.cs" />
<Compile Include="Documentation\Examples\Linq\Clone.cs" />
<Compile Include="Documentation\Examples\Linq\CreateJsonDynamic.cs" />
<Compile Include="Documentation\Examples\Linq\QueryJsonDynamic.cs" />
<Compile Include="Documentation\Examples\Linq\SerializeWithLinq.cs" />
<Compile Include="Documentation\Examples\Linq\CreateJsonCollectionInitializer.cs" />
<Compile Include="Documentation\Examples\Linq\CreateReader.cs" />
<Compile Include="Documentation\Examples\Linq\CreateWriter.cs" />
<Compile Include="Documentation\Examples\Linq\DeepEquals.cs" />
<Compile Include="Documentation\Examples\Linq\DeserializeWithLinq.cs" />
<Compile Include="Documentation\Examples\Linq\FromObject.cs" />
<Compile Include="Documentation\Examples\Linq\CreateJsonJTokenWriter.cs" />
<Compile Include="Documentation\Examples\Linq\JObjectProperties.cs" />
<Compile Include="Documentation\Examples\Linq\JValueValue.cs" />
<Compile Include="Documentation\Examples\Linq\ModifyJson.cs" />
<Compile Include="Documentation\Examples\Linq\ToObjectComplex.cs" />
<Compile Include="Documentation\Examples\Linq\ToObjectGeneric.cs" />
<Compile Include="Documentation\Examples\Linq\JValueCast.cs" />
<Compile Include="Documentation\Examples\Linq\ParseJsonAny.cs" />
<Compile Include="Documentation\Examples\Linq\ParseJsonArray.cs" />
<Compile Include="Documentation\Examples\Linq\CreateJsonAnonymousObject.cs" />
<Compile Include="Documentation\Examples\Linq\CreateJsonDeclaratively.cs" />
<Compile Include="Documentation\Examples\Linq\CreateJsonManually.cs" />
<Compile Include="Documentation\Examples\Linq\ParseJsonObject.cs" />
<Compile Include="Documentation\Examples\Linq\ToObjectType.cs" />
<Compile Include="Documentation\Examples\Linq\ToString.cs" />
<Compile Include="Documentation\Examples\Linq\ToStringJsonConverter.cs" />
<Compile Include="Documentation\Examples\Linq\WriteToJsonFile.cs" />
<Compile Include="Documentation\Examples\Linq\ReadJson.cs" />
<Compile Include="Documentation\Examples\SerializeDictionary.cs" />
<Compile Include="Documentation\Examples\CustomContractResolver.cs" />
<Compile Include="Documentation\Examples\DataContractAndDataMember.cs" />
<Compile Include="Documentation\Examples\DefaultValueAttributeIgnore.cs" />
<Compile Include="Documentation\Examples\DefaultValueHandlingIgnore.cs" />
<Compile Include="Documentation\Examples\DeserializeAnonymousType.cs" />
<Compile Include="Documentation\Examples\DeserializeConstructorHandling.cs" />
<Compile Include="Documentation\Examples\DeserializeMissingMemberHandling.cs" />
<Compile Include="Documentation\Examples\DeserializeWithJsonSerializerToFile.cs" />
<Compile Include="Documentation\Examples\DeserializeCollection.cs" />
<Compile Include="Documentation\Examples\DeserializeDictionary.cs" />
<Compile Include="Documentation\Examples\DeserializeObject.cs" />
<Compile Include="Documentation\Examples\ErrorHandlingEvent.cs" />
<Compile Include="Documentation\Examples\JsonConverterAttributeClass.cs" />
<Compile Include="Documentation\Examples\JsonObjectAttributeOptIn.cs" />
<Compile Include="Documentation\Examples\JsonPropertyName.cs" />
<Compile Include="Documentation\Examples\JsonPropertyOrder.cs" />
<Compile Include="Documentation\Examples\JsonPropertyItemLevelSetting.cs" />
<Compile Include="Documentation\Examples\JsonPropertyPropertyLevelSetting.cs" />
<Compile Include="Documentation\Examples\JsonPropertyRequired.cs" />
<Compile Include="Documentation\Examples\NullValueHandlingIgnore.cs" />
<Compile Include="Documentation\Examples\PopulateObject.cs" />
<Compile Include="Documentation\Examples\PropertyJsonIgnore.cs" />
<Compile Include="Documentation\Examples\ReferenceLoopHandlingIgnore.cs" />
<Compile Include="Documentation\Examples\ReferenceLoopHandlingObject.cs" />
<Compile Include="Documentation\Examples\SerializationCallbackAttributes.cs" />
<Compile Include="Documentation\Examples\DeserializeCustomCreationConverter.cs" />
<Compile Include="Documentation\Examples\SerializeContractResolver.cs" />
<Compile Include="Documentation\Examples\SerializeDateTimeZoneHandling.cs" />
<Compile Include="Documentation\Examples\JsonConverterAttributeProperty.cs" />
<Compile Include="Documentation\Examples\SerializeSerializationBinder.cs" />
<Compile Include="Documentation\Examples\SerializeCollection.cs" />
<Compile Include="Documentation\Examples\SerializeDateFormatHandling.cs" />
<Compile Include="Documentation\Examples\SerializeObject.cs" />
<Compile Include="Documentation\Examples\SerializeToBson.cs" />
<Compile Include="Documentation\Examples\SerializeTypeNameHandling.cs" />
<Compile Include="Documentation\Examples\SerializeUnindentedJson.cs" />
<Compile Include="Documentation\Examples\SerializeWithJsonConverters.cs" />
<Compile Include="Documentation\Examples\SerializeWithJsonSerializerToFile.cs" />
<Compile Include="Documentation\Examples\TraceWriter.cs" />
<Compile Include="Documentation\TraceWriterTests.cs" />
<Compile Include="Documentation\JsonNetVsWindowsDataJsonTests.cs" />
<Compile Include="Documentation\PerformanceTests.cs" />
@@ -76,5 +76,5 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC
[assembly: AssemblyFileVersion("4.5.11.15631")]
[assembly: AssemblyFileVersion("4.5.11.15716")]
#endif
@@ -565,5 +565,85 @@ namespace Newtonsoft.Json.Tests.Schema
Assert.AreEqual(JsonSchemaType.Object, schema.Properties["slash"].Type);
Assert.AreEqual(JsonSchemaType.Array, schema.Properties["percent"].Type);
}
[Test]
public void References_Array()
{
string json = @"{
""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}],
""properties"": {
""array"": {""$ref"": ""#/array/0""},
""arrayprop"": {""$ref"": ""#/array/1/prop""}
}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual(JsonSchemaType.Integer, schema.Properties["array"].Type);
Assert.AreEqual(JsonSchemaType.Object, schema.Properties["arrayprop"].Type);
}
[Test]
public void References_IndexTooBig()
{
// JsonException : Could not resolve schema reference '#/array/10'.
string json = @"{
""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}],
""properties"": {
""array"": {""$ref"": ""#/array/0""},
""arrayprop"": {""$ref"": ""#/array/10""}
}
}";
ExceptionAssert.Throws<JsonException>(
"Could not resolve schema reference '#/array/10'.",
() =>
{
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
builder.Read(new JsonTextReader(new StringReader(json)));
});
}
[Test]
public void References_IndexNegative()
{
string json = @"{
""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}],
""properties"": {
""array"": {""$ref"": ""#/array/0""},
""arrayprop"": {""$ref"": ""#/array/-1""}
}
}";
ExceptionAssert.Throws<JsonException>(
"Could not resolve schema reference '#/array/-1'.",
() =>
{
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
builder.Read(new JsonTextReader(new StringReader(json)));
});
}
[Test]
public void References_IndexNotInteger()
{
string json = @"{
""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}],
""properties"": {
""array"": {""$ref"": ""#/array/0""},
""arrayprop"": {""$ref"": ""#/array/one""}
}
}";
ExceptionAssert.Throws<JsonException>(
"Could not resolve schema reference '#/array/one'.",
() =>
{
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
builder.Read(new JsonTextReader(new StringReader(json)));
});
}
}
}
@@ -54,8 +54,6 @@ namespace Newtonsoft.Json.Tests.Schema
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string baseTestPath = Path.Combine(baseDirectory, "Schema", "Specs");
Console.WriteLine("Loading JSON Schema tests from " + baseTestPath);
string[] testFiles = Directory.GetFiles(baseTestPath, "*.json", SearchOption.AllDirectories);
// read through each of the *.json test files and extract the test details
@@ -23,6 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;
@@ -119,6 +120,89 @@ namespace Newtonsoft.Json.Tests.Schema
}", writtenJson);
}
[Test]
public void Extends_Multiple()
{
string json = @"{
""type"":""object"",
""extends"":{""type"":""string""},
""additionalProperties"":{""type"":""string""}
}";
JsonSchema s = JsonSchema.Parse(json);
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
string newJson = s.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""additionalProperties"": {
""type"": ""string""
},
""extends"": {
""type"": ""string""
}
}", newJson);
json = @"{
""type"":""object"",
""extends"":[{""type"":""string""}],
""additionalProperties"":{""type"":""string""}
}";
s = JsonSchema.Parse(json);
writer = new StringWriter();
jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
newJson = s.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""additionalProperties"": {
""type"": ""string""
},
""extends"": {
""type"": ""string""
}
}", newJson);
json = @"{
""type"":""object"",
""extends"":[{""type"":""string""},{""type"":""object""}],
""additionalProperties"":{""type"":""string""}
}";
s = JsonSchema.Parse(json);
writer = new StringWriter();
jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
newJson = s.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""additionalProperties"": {
""type"": ""string""
},
""extends"": [
{
""type"": ""string""
},
{
""type"": ""object""
}
]
}", newJson);
}
[Test]
public void WriteTo_AdditionalProperties()
{
@@ -7216,6 +7216,108 @@ Parameter name: value",
}
}", json);
}
[Test]
public void DeserializeDecimal()
{
JsonTextReader reader = new JsonTextReader(new StringReader("1234567890.123456"));
var settings = new JsonSerializerSettings();
var serialiser = JsonSerializer.Create(settings);
decimal? d = serialiser.Deserialize<decimal?>(reader);
Assert.AreEqual(1234567890.123456m, d);
}
[Test]
public void DontSerializeStaticFields()
{
string json =
JsonConvert.SerializeObject(new AnswerFilterModel(), Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
IgnoreSerializableAttribute = false
}
});
Assert.AreEqual(@"{
""<Active>k__BackingField"": false,
""<Ja>k__BackingField"": false,
""<Handlungsbedarf>k__BackingField"": false,
""<Beratungsbedarf>k__BackingField"": false,
""<Unzutreffend>k__BackingField"": false,
""<Unbeantwortet>k__BackingField"": false
}", json);
}
}
public enum Antworten
{
First,
Second
}
public class SelectListItem
{
public string Text { get; set; }
public string Value { get; set; }
public bool Selected { get; set; }
}
[Serializable]
public class AnswerFilterModel
{
[NonSerialized]
private readonly IList answerValues;
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
public AnswerFilterModel()
{
this.answerValues = (from answer in Enum.GetNames(typeof(Antworten))
select new SelectListItem { Text = answer, Value = answer, Selected = false })
.ToList();
}
/// <summary>
/// Gets or sets a value indicating whether active.
/// </summary>
public bool Active { get; set; }
/// <summary>
/// Gets or sets a value indicating whether ja.
/// nach bisherigen Antworten.
/// </summary>
public bool Ja { get; set; }
/// <summary>
/// Gets or sets a value indicating whether handlungsbedarf.
/// </summary>
public bool Handlungsbedarf { get; set; }
/// <summary>
/// Gets or sets a value indicating whether beratungsbedarf.
/// </summary>
public bool Beratungsbedarf { get; set; }
/// <summary>
/// Gets or sets a value indicating whether unzutreffend.
/// </summary>
public bool Unzutreffend { get; set; }
/// <summary>
/// Gets or sets a value indicating whether unbeantwortet.
/// </summary>
public bool Unbeantwortet { get; set; }
/// <summary>
/// Gets the answer values.
/// </summary>
public IEnumerable AnswerValues
{
get { return this.answerValues; }
}
}
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
+5 -3
View File
@@ -96,11 +96,13 @@ namespace Newtonsoft.Json.Tests
{
public static void IsInstanceOfType(Type t, object instance)
{
#if !NETFX_CORE
#if (WINDOWS_PHONE || SILVERLIGHT)
Assert.IsInstanceOfType(t, instance);
#else
#elif NETFX_CORE
if (!instance.GetType().IsAssignableFrom(t))
throw new Exception("Blah");
throw new Exception("Not instance of type");
#else
Assert.IsInstanceOf(t, instance);
#endif
}
@@ -90,7 +90,7 @@ namespace Newtonsoft.Json
return Create(reader as IJsonLineInfo, reader.Path, message, ex);
}
internal static new JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex)
internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex)
{
message = JsonPosition.FormatMessage(lineInfo, path, message);
+45 -39
View File
@@ -167,6 +167,51 @@ namespace Newtonsoft.Json.Linq
internal set { _previous = value; }
}
/// <summary>
/// Gets the path of the JSON token.
/// </summary>
public string Path
{
get
{
if (Parent == null)
return string.Empty;
IList<JToken> ancestors = Ancestors().Reverse().ToList();
ancestors.Add(this);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ancestors.Count; i++)
{
JToken current = ancestors[i];
JToken next = (i + 1 < ancestors.Count) ? ancestors[i + 1] : null;
if (next != null)
{
switch (current.Type)
{
case JTokenType.Property:
JProperty property = (JProperty)current;
if (sb.Length > 0)
sb.Append(".");
sb.Append(property.Name);
break;
case JTokenType.Array:
case JTokenType.Constructor:
int index = ((IList<JToken>)current).IndexOf(next);
sb.Append("[" + index + "]");
break;
}
}
}
return sb.ToString();
}
}
internal JToken()
{
}
@@ -1700,44 +1745,5 @@ namespace Newtonsoft.Json.Linq
{
return CloneToken();
}
public string Path
{
get
{
IList<JToken> ancestors = Ancestors().Reverse().ToList();
ancestors.Add(this);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ancestors.Count; i++)
{
JToken current = ancestors[i];
JToken next = (i + 1 < ancestors.Count) ? ancestors[i + 1] : null;
if (next != null)
{
switch (current.Type)
{
case JTokenType.Property:
JProperty property = (JProperty) current;
if (sb.Length > 0)
sb.Append(".");
sb.Append(property.Name);
break;
case JTokenType.Array:
case JTokenType.Constructor:
int index = ((IList<JToken>)current).IndexOf(next);
sb.Append("[" + index + "]");
break;
}
}
}
return sb.ToString();
}
}
}
}
@@ -90,7 +90,7 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC
[assembly: AssemblyFileVersion("4.5.11.15631")]
[assembly: AssemblyFileVersion("4.5.11.15716")]
#endif
[assembly: CLSCompliant(true)]
+1 -1
View File
@@ -201,7 +201,7 @@ namespace Newtonsoft.Json.Schema
/// <value>The format.</value>
public string Format { get; set; }
public string Location { get; set; }
internal string Location { get; set; }
private readonly string _internalId = Guid.NewGuid().ToString("N");
@@ -120,7 +120,7 @@ namespace Newtonsoft.Json.Schema
else if (currentToken.Type == JTokenType.Array || currentToken.Type == JTokenType.Constructor)
{
int index;
if (int.TryParse(part, out index))
if (int.TryParse(part, out index) && index >= 0 && index < currentToken.Count())
currentToken = currentToken[index];
else
currentToken = null;
@@ -319,7 +319,8 @@ namespace Newtonsoft.Json.Serialization
// serialize all fields
foreach (MemberInfo member in allMembers)
{
if (member.MemberType() == MemberTypes.Field)
FieldInfo field = member as FieldInfo;
if (field != null && !field.IsStatic)
serializableMembers.Add(member);
}
}