diff --git a/Doc/ContractResolver.aml b/Doc/ContractResolver.aml new file mode 100644 index 00000000..898ec208 --- /dev/null +++ b/Doc/ContractResolver.aml @@ -0,0 +1,48 @@ + + + + + + The IContractResolver interface provides a way to customize how the + JsonSerializer serializes and deserializes .NET objects to JSON. + Implementing the IContractResolver interface and then assigning an + instance to a JsonSerializer lets you control whether the object is + serialized as a JSON object or JSON array, what object members should be + serialized, how they are serialized and what they are called. + + +
+ DefaultContractResolver + + + The T:Newtonsoft.Json.Serialization.DefaultContractResolver + is the default resolver used by the + serializer. It provides many avenues of extensibility in the form of + virtual methods that can be overriden. + +
+
+ CamelCasePropertyNamesContractResolver + + + T:Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver + inherits from DefaultContractResolver and simply overrides the JSON + property name to be written in +camelcase +http://en.wikipedia.org/wiki/CamelCase +_blank +. + + + +
+
+
\ No newline at end of file diff --git a/Doc/ContractResolver.html b/Doc/ContractResolver.html deleted file mode 100644 index 99ef6deb..00000000 --- a/Doc/ContractResolver.html +++ /dev/null @@ -1,92 +0,0 @@ - - - - Contract Resolver - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Contract Resolvers
- -
- - - -

The IContractResolver interface provides a way to customize how the JsonSerializer serializes and deserializes .NET objects to JSON.

-

Implementing the IContractResolver interface and then assigning an instance to a JsonSerializer lets you control - whether the object is serialized as a JSON object or JSON array, what object members should be serialized, how they are serialized and what they are called.

- -

DefaultContractResolver

-

The DefaultContractResolver is the default resolver used by the serializer. It provides many avenues of extensibility in the form of virtual methods that can be overriden.

- -

CamelCasePropertyNamesContractResolver

-

CamelCasePropertyNamesContractResolver inherits from DefaultContractResolver and simply overrides the JSON property name to be written in camelcase.

- -
Product product = new Product
- -
                    {
- -
                      ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
- -
                      Name = "Widget",
- -
                      Price = 9.99m,
- -
                      Sizes = new[] {"Small", "Medium", "Large"}
- -
                    };
- -
 
- -
string json = 
- -
  JsonConvert.SerializeObject(
- -
    product,
- -
    Formatting.Indented,
- -
    new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
- -
  );
- -
 
- -
//{
- -
//  "name": "Widget",
- -
//  "expiryDate": "\/Date(1292868060000)\/",
- -
//  "price": 9.99,
- -
//  "sizes": [
- -
//    "Small",
- -
//    "Medium",
- -
//    "Large"
- -
//  ]
- -
//}
-
-
-
- - - -
- - - - \ No newline at end of file diff --git a/Doc/ConvertingJSONandXML.aml b/Doc/ConvertingJSONandXML.aml new file mode 100644 index 00000000..87a5f246 --- /dev/null +++ b/Doc/ConvertingJSONandXML.aml @@ -0,0 +1,59 @@ + + + + + Json.NET supports converting JSON to XML and vice versa using the + T:Newtonsoft.Json.Converters.XmlNodeConverter. + Elements, attributes, text, comments, character data, processing instructions, + namespaces and the XML declaration are all preserved when converting between the two. The + only caveat is that it is possible to lose the order of differently named nodes at the + same level when they are grouped together into an array. + +
+ Conversion Rules + + + + Elements remain unchanged. + Attributes are prefixed with an @ and should be at the start of the object. + Single child text nodes are a value directly against an element, otherwise they are accessed via #text. + The XML declaration and processing instructions are prefixed with ?. + Charater data, comments, whitespace and significate whitespace nodes are accessed via + #cdata-section, #comment, #whitespace and #significate-whitespace respectively. + Multiple nodes with the same name at the same level are grouped together into an array. + Empty elements are null. + + + +
+
+ SerializeXmlNode + + + The JsonConvert has two helper methods for converting between JSON and XML. The first is + Overload:Newtonsoft.Json.JsonConvert.SerializeXmlNode. + This method takes an XmlNode and serializes it to JSON text. + + + + +
+
+ DeserializeXmlNode + + + The second helper method on JsonConvert is + Overload:Newtonsoft.Json.JsonConvert.DeserializeXmlNode. + This method takes JSON text and deserializes it into a XmlNode. + + Because valid XML must have one root element the JSON passed to DeserializeXmlNode should + have one property in the root JSON object. If the root JSON object has multiple properties then + the overload that also takes an element name should be used. A root element with that name will + be inserted into the deserialized XmlNode. + + + + +
+
+
\ No newline at end of file diff --git a/Doc/ConvertingJSONandXML.html b/Doc/ConvertingJSONandXML.html deleted file mode 100644 index 5d93bd17..00000000 --- a/Doc/ConvertingJSONandXML.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - Converting between JSON and XML - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Converting between JSON and XML
- -
- -

Json.NET supports converting JSON to XML and vice versa using the - XmlNodeConverter.

- -

- Elements, attributes, text, comments, character data, processing instructions, - namespaces and the XML declaration are all preserved when converting between the - two. The only caveat is that it is possible to lose the order of differently - named nodes at the same level when they are grouped together into an array.

-

Conversion Rules

-
    -
  • Elements remain unchanged.
  • -
  • Attributes are prefixed with an @ and should be at the start of the object.
  • -
  • Single child text nodes are a value directly against an element, otherwise they - are accessed via #text.
  • -
  • The XML declaration and processing instructions are prefixed with ?.
  • -
  • Charater data, comments, whitespace and significate whitespace nodes are - accessed via #cdata-section, #comment, #whitespace and #significate-whitespace - respectively.
  • -
  • Multiple nodes with the same name at the same level are grouped together into an - array.
  • -
  • Empty elements are null.
  • -
- -

SerializeXmlNode

-

The JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode. This method takes an -XmlNode and serializes it to JSON text.

-
-
-
-
string xml = @"<?xml version=""1.0"" standalone=""no""?>
-
<root>
-
  <person id=""1"">
-
  <name>Alan</name>
-
  <url>http://www.google.com</url>
-
  </person>
-
  <person id=""2"">
-
  <name>Louis</name>
-
  <url>http://www.yahoo.com</url>
-
  </person>
-
</root>";
-
 
-
XmlDocument doc = new XmlDocument();
-
doc.LoadXml(xml);
-
 
-
string jsonText = JsonConvert.SerializeXmlNode(doc);
-
//{
-
//  "?xml": {
-
//    "@version": "1.0",
-
//    "@standalone": "no"
-
//  },
-
//  "root": {
-
//    "person": [
-
//      {
-
//        "@id": "1",
-
//        "name": "Alan",
-
//        "url": "http://www.google.com"
-
//      },
-
//      {
-
//        "@id": "2",
-
//        "name": "Louis",
-
//        "url": "http://www.yahoo.com"
-
//      }
-
//    ]
-
//  }
-
//}
-
- -
-
- -

DeserializeXmlNode

- -

The second helper method on JsonConvert is DeserializeXmlNode. This method takes - JSON text and deserializes it into a XmlNode.

-

Because valid XML must have one root element the JSON passed to - DeserializeXmlNode should have one property in the root JSON object. If the root - JSON object has multiple properties then the overload that also takes an element - name should be used. A root element with that name will be inserted into the - deserialized XmlNode.

- -
- -
- -
-
string json = @"{
-
  ""?xml"": {
-
    ""@version"": ""1.0"",
-
    ""@standalone"": ""no""
-
  },
-
  ""root"": {
-
    ""person"": [
-
      {
-
        ""@id"": ""1"",
-
        ""name"": ""Alan"",
-
        ""url"": ""http://www.google.com""
-
      },
-
      {
-
        ""@id"": ""2"",
-
        ""name"": ""Louis"",
-
        ""url"": ""http://www.yahoo.com""
-
      }
-
    ]
-
  }
-
}";
-
 
-
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
-
// <?xml version="1.0" standalone="no"?>
-
// <root>
-
//   <person id="1">
-
//   <name>Alan</name>
-
//   <url>http://www.google.com</url>
-
//   </person>
-
//   <person id="2">
-
//   <name>Louis</name>
-
//   <url>http://www.yahoo.com</url>
-
//   </person>
-
// </root>
-
- - -
-
- - -
- - - - \ No newline at end of file diff --git a/Doc/CustomCreationConverter.aml b/Doc/CustomCreationConverter.aml new file mode 100644 index 00000000..3b4bc87b --- /dev/null +++ b/Doc/CustomCreationConverter.aml @@ -0,0 +1,29 @@ + + + + + + The CustomCreationConverter is a JsonConverter that provides a way + to customize how an object is created during JSON deserialization. Once + the object has been created it will then have values populated onto it by + the serializer. + + +
+ Example + + + This is an extremely simple example. A more complicated scenario + could involve an object factory or service locator which resolves the + object at runtime. + + +
+
+
\ No newline at end of file diff --git a/Doc/CustomCreationConverter.html b/Doc/CustomCreationConverter.html deleted file mode 100644 index edc403b0..00000000 --- a/Doc/CustomCreationConverter.html +++ /dev/null @@ -1,99 +0,0 @@ - - - - CustomCreationConverter - - - - - - -
- Json.NET - Quick Starts & API Documentation
- CustomCreationConverter
- -
- - -

- The CustomCreationConverter is a JsonConverter that provides a way to customize how an object is created - during JSON deserialization. - Once the object has been created it will then have values populated onto it by the serializer. -

- -
-
-
public interface IPerson
-
{
-
  string FirstName { get; set; }
-
  string LastName { get; set; }
-
  DateTime BirthDate { get; set; }
-
}
-
 
-
public class Employee : IPerson
-
{
-
  public string FirstName { get; set; }
-
  public string LastName { get; set; }
-
  public DateTime BirthDate { get; set; }
-
 
-
  public string Department { get; set; }
-
  public string JobTitle { get; set; }
-
}
-
 
-
public class PersonConverter : CustomCreationConverter<IPerson>
-
{
-
  public override IPerson Create(Type objectType)
-
  {
-
    return new Employee();
-
  }
-
}
-
-
- -

-This is an extremely simple example. A more complicated scenario could involve an object factory or service locator - which resolves the object at runtime. -

- -
-
-
//[
-
//  {
-
//    "FirstName": "Maurice",
-
//    "LastName": "Moss",
-
//    "BirthDate": "\/Date(252291661000)\/",
-
//    "Department": "IT",
-
//    "JobTitle": "Support"
-
//  },
-
//  {
-
//    "FirstName": "Jen",
-
//    "LastName": "Barber",
-
//    "BirthDate": "\/Date(258771661000)\/",
-
//    "Department": "IT",
-
//    "JobTitle": "Manager"
-
//  }
-
//]
-
 
-
List<IPerson> people = JsonConvert.DeserializeObject<List<IPerson>>(json, new PersonConverter());
-
 
-
IPerson person = people[0];
-
 
-
Console.WriteLine(person.GetType());
-
// Newtonsoft.Json.Tests.Employee
-
 
-
Console.WriteLine(person.FirstName);
-
// Maurice
-
 
-
Employee employee = (Employee)person;
-
 
-
Console.WriteLine(employee.JobTitle);
-
// Support
-
-
- - -
- - - - \ No newline at end of file diff --git a/Doc/DatesInJSON.aml b/Doc/DatesInJSON.aml new file mode 100644 index 00000000..fc122a9d --- /dev/null +++ b/Doc/DatesInJSON.aml @@ -0,0 +1,93 @@ + + + + + + DateTimes in JSON are hard. + The problem comes from the +JSON spec +http://www.ietf.org/rfc/rfc4627.txt +_blank + itself: there is no literal + syntax for dates in JSON. The spec has objects, arrays, strings, integers + and floats, but it defines no standard for what a date looks like. + + +
+ Dates and Json.NET + + + The default format used by Json.NET is the +ISO 8601 standard +http://en.wikipedia.org/wiki/ISO_8601 +_blank +: 2012-03-19T07:22Z. + Prior to Json.NET 4.5 dates were written using the Microsoft + format: "\/Date(1198908717056)\/". If you want to use this format, or + you want to maintain compatibility with Microsoft JSON serializers or + older versions of Json.NET then change the + T:Newtonsoft.Json.DateFormatHandling + setting to MicrosoftDateFormat. + Json.NET also has the T:Newtonsoft.Json.DateTimeZoneHandling + setting. This can be + used to convert DateTime's kind when serializing, e.g. set + DateTimeZoneHandling to Utc to serialize all DateTimes as UTC dates. + +
+
+ DateTime JsonConverters + + + With no standard for dates in JSON, the number of possible + different formats when interoping with other systems is endless. + Fortunately Json.NET has a solution to deal with reading and writing + custom dates: JsonConverters. A JsonConverter is used to override how a + type is serialized. + + + + Simply pass the JsonConverter you wish to use to the Json.NET + serializer. + +
+
+ JavaScriptDateTimeConverter + + The JavaScriptDateTimeConverter class is one of the two DateTime + JsonConverters that come with Json.NET. This converter serializes a + DateTime as a +JavaScript Date object +http://msdn.microsoft.com/en-us/library/cd9w2te4.aspx +_blank +: new Date(1234656000000) + Technically this is invalid JSON according to the spec but all + browsers, and some JSON frameworks, including Json.NET, support it. + +
+
+ IsoDateTimeConverter + + + Since Json.NET 4.5 dates are written using the ISO 8601 + format by default and using this converter is unnecessary. + + IsoDateTimeConverter seralizes a DateTime to an +ISO 8601 +http://en.wikipedia.org/wiki/ISO_8601 +_blank + formatted + string: "2009-02-15T00:00:00Z" + The IsoDateTimeConverter class has a property, DateTimeFormat, to + further customize the formatted string. + +
+
+
\ No newline at end of file diff --git a/Doc/DatesInJSON.html b/Doc/DatesInJSON.html deleted file mode 100644 index d9d86266..00000000 --- a/Doc/DatesInJSON.html +++ /dev/null @@ -1,107 +0,0 @@ - - - - Serializing Dates in JSON - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Serializing Dates in JSON
- -
- -

DateTimes in JSON are hard.

-

- The problem comes from the JSON spec itself: there is no literal syntax for dates in JSON. The spec has objects, arrays, strings, integers and floats, but it defines no standard for what a date looks like.

-

The default format used by Json.NET - is the ISO 8601 standard: 2012-03-19T07:22Z. You can read more about it here.

-

Prior to Json.NET 4.5 dates were written using the Microsoft format: - "\/Date(1198908717056)\/". If you want to use this format, or you want to - maintain compatibility with Microsoft JSON serializers or older versions of - Json.NET then change the DateFormatHandling setting to MicrosoftDateFormat.

-

Json.NET also has the DateTimeZoneHandling setting. This can be used to convert - DateTime's kind when serializing, e.g. set DateTimeZoneHandling to Utc to - serialize all DateTimes as UTC dates.

- -

DateTime JsonConverters

-

With no standard for dates in JSON, the number of possible different formats when interoping with other systems is endless. Fortunately Json.NET has a solution to deal with reading and writing custom dates: JsonConverters. A JsonConverter is used to override how a type is serialized.

- -
-
-
-
public class LogEntry
-
{
-
  public string Details { get; set; }
- -
  public DateTime LogDate { get; set; }
-
}
-
 
-
[Test]
- -
public void WriteJsonDates()
-
{
-
  LogEntry entry = new LogEntry
-
  {
- -
    LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
-
    Details = "Application started."
-
  };
-
 
- -
  // default as of Json.NET 4.5
-
  string isoJson = JsonConvert.SerializeObject(entry);
-
  // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}
- -
 
-
  JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
-
  {
-
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
-
  };
-
  string microsoftJson = JsonConvert.SerializeObject(entry, microsoftDateFormatSettings);
-
  // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
- -
 
-
  string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
-
  // {"Details":"Application started.","LogDate":new Date(1234656000000)}
- -
}
-
-
-
-

Simply pass the JsonConverter you wish to use to the Json.NET serializer.

-

JavaScriptDateTimeConverter

-

The JavaScriptDateTimeConverter class is one of the two DateTime JsonConverters that come with Json.NET. This converter serializes a DateTime as a JavaScript Date object.

-
-
-
-
new Date(1234656000000)
- -
-
-
-

Technically this is invalid JSON according to the spec but all browsers, and some JSON frameworks, including Json.NET, support it.

-

IsoDateTimeConverter

-

IsoDateTimeConverter seralizes a DateTime to an ISO 8601 formatted string. - Note that since Json.NET 4.5 dates are written using the ISO 8601 format by - default and using this converter is unnecessary.

-
-
-
-
"2009-02-15T00:00:00Z"
- -
-
-
-

The IsoDateTimeConverter class has a property, DateTimeFormat, to further customize the formatted string.

- - - -
- - - - \ No newline at end of file diff --git a/Doc/Introduction.aml b/Doc/Introduction.aml new file mode 100644 index 00000000..006480a9 --- /dev/null +++ b/Doc/Introduction.aml @@ -0,0 +1,92 @@ + + + + + + Json.NET is a popular high-performance JSON framework for .NET + + +
+ Benefits and Features + + + + Flexible JSON serializer for converting between .NET objects and JSON + + + LINQ to JSON for manually reading and writing JSON + + + High performance, faster than .NET's built-in JSON serializers + + + Write indented, easy to read JSON + + + Convert JSON to and from XML + + + Supports .NET 2, .NET 3.5, .NET 4, Silverlight, Windows Phone and Windows 8 Metro + + + +The JSON serializer is a good choice when the JSON you are reading or writing maps closely to a .NET class. +LINQ to JSON is good for situations where you are only interested in +getting values from JSON, you don't have a class to serialize or deserialize to, +or the JSON is radically different from your class and you need to manually read +and write from your objects. + +
+ +
+ History + Json.NET grew out of projects I was working on in late 2005 involving JavaScript, + AJAX and .NET. At the time there were no libraries for working with JavaScript in + .NET so I began to grow my own. + Starting out as a couple of static methods for escaping JavaScript strings, Json.NET + evolved as features were added. To add support for reading JSON a major refactor + was required and Json.NET will split into the three major classes it still uses + today, JsonReader, JsonWriter and JsonSerializer. + Json.NET was first released in June 2006. Since then Json.NET has been downloaded + thousands of times by developers and is used in a number of major projects open + source projects including + MonoRail + http://www.castleproject.org/projects/monorail + _blank + , + Castle Project's MVC web framework, and + Mono + http://www.mono-project.com/ + _blank + , + an open source implementation + of the .NET framework. + + James Newton-King + http://twitter.com/jamesnk + _blank + + +
+ +
+ Donate + Json.NET is a free open source project developed in my own time. + I really appreciate your feedback and support for Json.NET and its future development. +
+ + +

+ + Donate + +

+
+ +
+
\ No newline at end of file diff --git a/Doc/Introduction.html b/Doc/Introduction.html deleted file mode 100644 index 0282159a..00000000 --- a/Doc/Introduction.html +++ /dev/null @@ -1,68 +0,0 @@ - - - Introduction - - - - -
- Json.NET - Quick Starts & API Documentation
- Introduction
-
- -

- Json.NET makes working with JSON formatted data in .NET - simple. Quickly read and write JSON using LINQ to JSON or serialize - your .NET objects with a single method call using the JsonSerializer.

-

- Features

-
    -
  • Flexible JSON serializer to convert .NET objects to JSON and back again
  • -
  • LINQ to JSON for reading and writing JSON
  • -
  • Writes indented, easy to read JSON
  • -
  • Convert JSON to and from XML
  • -
  • Supports Silverlight and the Compact Framework
  • -
-

The JSON serializer is a good choice when the JSON you are reading or writing maps closely - to a .NET class. The serializer automatically reads and writes JSON for the class.

-

- For situations where you are only interested in getting values from JSON, don't - have a class to serialize or deserialize to, or the JSON is radically different - from your class and you need to manually read and write from your objects then - LINQ to JSON is what you should use. LINQ to JSON allows you to easily read, - create and modify JSON in .NET.

-

- History

-

- Json.NET grew out of projects I was working on in late 2005 involving JavaScript, - AJAX and .NET. At the time there were no libraries for working with JavaScript in - .NET so I began to grow my own.

-

- Starting out as a couple of static methods for escaping JavaScript strings, Json.NET - evolved as features were added. To add support for reading JSON a major refactor - was required and Json.NET will split into the three major classes it still uses - today, JsonReader, JsonWriter and JsonSerializer. -

-

- Json.NET was first released in June 2006. Since then Json.NET has been downloaded - thousands of times by developers and is used in a number of major projects open - source projects including MonoRail, - Castle Project's MVC web framework, and Mono, - an open source implementation - of the .NET framework.

-

- ~ James Newton-King

-

- Donate

-

- Json.NET is a free open source project that I have developed in my personal time.

-

- I really appreciate your feedback and support for Json.NET and its future development.

-

- Donate -

- -
- - diff --git a/Doc/LINQtoJSON.aml b/Doc/LINQtoJSON.aml new file mode 100644 index 00000000..09be4a8d --- /dev/null +++ b/Doc/LINQtoJSON.aml @@ -0,0 +1,72 @@ + + + + + LINQ to JSON is a programming API for working with JSON objects. + The API has been designed with LINQ in mind to enable to quick querying + and creation of JSON objects. LINQ to JSON sits under the + N:Newtonsoft.Json.Linq + namespace. + + +
+ Creating JSON + + + There are a number of different options when it comes to creating + JSON using LINQ to JSON. The first to create objects imperatively. You + have total control but it is more verbose than other options. + + + + Another option is to create JSON objects declaratively. + + + + You can create a JSON object from a non-JSON type using the + Overload:Newtonsoft.Json.Linq.JObject.FromObject + method. + + + + Finally JSON objects can be created from a string use the + M:Newtonsoft.Json.Linq.JToken.Parse(System.String) + method. + + + +
+
+ Querying JSON + + + The properties and methods that are the most useful when querying JSON + objects are + M:Newtonsoft.Json.Linq.JToken.Children + and + P:Newtonsoft.Json.Linq.JToken.Item(System.Object) + . + + Children returns all the children of that object. If it is a + JObject it will return a collection of properties to work with and if + it is a JArray you will get a collection of the array's values. + + The index property is used to get a specific child, either by + index position for JSON arrays or property name for JSON objects. + + + + LINQ to JSON can also be used to manually convert from JSON to a .NET object. + + + + Manually serializing and deserializing between .NET objects is most useful when + working with JSON that doesn't closely match your .NET objects. + + + +
+
+
\ No newline at end of file diff --git a/Doc/LINQtoJSON.html b/Doc/LINQtoJSON.html deleted file mode 100644 index c80d3b7f..00000000 --- a/Doc/LINQtoJSON.html +++ /dev/null @@ -1,254 +0,0 @@ - - - - LINQ to JSON - - - - - - -
- Json.NET - Quick Starts & API Documentation
- LINQ to JSON
- -
- - -

LINQ to JSON is a programming API for working with JSON objects. The API has been designed with LINQ in mind to enable to quick querying and creation of JSON objects. LINQ to JSON sits under the Newtonsoft.Json.Linq namespace.

- -

Creating JSON

-

There are a number of different options when it comes to creating JSON using LINQ to JSON. The first to create objects imperatively. You have total control but it is more verbose than other options.

- -
- -
-
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();
-
// [
-
//   "Manual text",
-
//   "\/Date(958996800000+1200)\/"
-
// ]
-
- -
- -

Another option is to create JSON objects declaratively.

- - -
- -
-
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"
-
//        ]
-
//      }
-
//    ]
-
//  }
-
//}
-
- -
- -

You can create a JSON object from a non-JSON type using the FromObject method.

- -
- -
-
JObject o = JObject.FromObject(new
-
{
-
  channel = new
-
  {
-
    title = "James Newton-King",
-
    link = "http://james.newtonking.com",
-
    description = "James Newton-King's blog.",
-
    item =
-
        from p in posts
-
        orderby p.Title
-
        select new
-
        {
-
          title = p.Title,
-
          description = p.Description,
-
          link = p.Link,
-
          category = p.Categories
-
        }
-
  }
-
});
-
- -
- -

Finally JSON objects can be created from a string use the Parse method.

- -
- -
-
string json = @"{
-
  CPU: 'Intel',
-
  Drives: [
-
    'DVD read/writer',
-
    ""500 gigabyte hard drive""
-
  ]
-
}";
-
 
-
JObject o = JObject.Parse(json);
-
- -
- -

Querying JSON

- - -

The properties methods that are the most useful when querying JSON objects are - the Children - method and the property index.

-

Children returns all the children of that object. If it is a JObject it will - return a collection of properties to work with and if it is a JArray you will - get a collection of the array's values.

-

The property index is used to get a specific child, either by index position for JSON arrays or property name for JSON objects.

- -
- -
-
var postTitles =
-
  from p in rss["channel"]["item"].Children()
-
  select (string)p["title"];
-
 
-
foreach (var item in postTitles)
-
{
-
  Console.WriteLine(item);
-
}
-
 
-
//LINQ to JSON beta
-
//Json.NET 1.3 + New license + Now on CodePlex
-
 
-
var categories =
-
  from c in rss["channel"]["item"].Children()["category"].Values<string>()
-
  group c by c into g
-
  orderby g.Count() descending
-
  select new { Category = g.Key, Count = g.Count() };
-
 
-
foreach (var c in categories)
-
{
-
  Console.WriteLine(c.Category + " - Count: " + c.Count);
-
}
-
 
-
//Json.NET - Count: 2
-
//LINQ - Count: 1
-
//CodePlex - Count: 1
-
- -
- -

LINQ to JSON can also be used to manually convert from JSON to a .NET object.

- -
-
-
public class Shortie
-
{
-
  public string Original { get; set; }
-
  public string Shortened { get; set; }
-
  public string Short { get; set; }
-
  public ShortieException Error { get; set; }
-
}
-
 
-
public class ShortieException
-
{
-
  public int Code { get; set; }
-
  public string ErrorMessage { get; set; }
-
}
-
-
- -

Manually serializing and deserializing between .NET objects is most useful when working with JSON that doesn't closely match your .NET objects.

- -
- -
-
string jsonText = @"{
-
  ""short"":{
-
    ""original"":""http://www.foo.com/"",
-
    ""short"":""krehqk"",
-
    ""error"":{
-
      ""code"":0,
-
      ""msg"":""No action taken""}
-
}";
-
 
-
JObject json = JObject.Parse(jsonText);
-
 
-
Shortie shortie = new Shortie
-
                  {
-
                    Original = (string)json["short"]["original"],
-
                    Short = (string)json["short"]["short"],
-
                    Error = new ShortieException
-
                            {
-
                              Code = (int)json["short"]["error"]["code"],
-
                              ErrorMessage = (string)json["short"]["error"]["msg"]
-
                            }
-
                  };
-
 
-
Console.WriteLine(shortie.Original);
-
// http://www.foo.com/
-
 
-
Console.WriteLine(shortie.Error.ErrorMessage);
-
// No action taken
-
- -
- - -
- - - - \ No newline at end of file diff --git a/Doc/PreserveObjectReferences.aml b/Doc/PreserveObjectReferences.aml new file mode 100644 index 00000000..77e08e6e --- /dev/null +++ b/Doc/PreserveObjectReferences.aml @@ -0,0 +1,72 @@ + + + + + + By default Json.NET will serialize all objects it encounters by value. + If a list contains two Person references, and both references point to the + same object then the JsonSerializer will write out all the names and values + for each reference. + + + + In most cases this is the desired result but in certain scenarios + writing the second item in the list as a reference to the first is a better + solution. If the above JSON was deserialized now then the returned list would + contain two completely separate Person objects with the same values. Writing + references by value will also cause problems on objects where a circular + reference occurs. + + +
+ PreserveReferencesHandling + + Settings PreserveReferencesHandling will track object references + when serializing and deserializing JSON. + + + + The first Person in the list is serizlied with the addition of an + object Id. The second Person in JSON is now only a reference to the first. + With PreserveReferencesHandling on now only one Person object is created + on deserialization and the list contains two references to it, mirroring + what we started with. + +
+ +
+ IsReference + + The PreserveReferencesHandling setting on the JsonSerializer will + change how all objects are serialized and deserialized. For fine grain + control over which objects and members should be serialized as a + reference there is the IsReference property on the JsonObjectAttribute, + JsonArrayAttribute and JsonPropertyAttribute. + + Setting IsReference on JsonObjectAttribute or JsonArrayAttribute to + true will mean the JsonSerializer will always serialize the type the + attribute is against as a reference. Setting IsReference on the + JsonPropertyAttribute to true will serialize only that property as a + reference. + + + +
+ +
+ IReferenceResolver + + To customize how references are generated and resolved the + T:Newtonsoft.Json.Serialization.IReferenceResolver + interface is available to inherit from and use with + the JsonSerializer. + +
+
+
\ No newline at end of file diff --git a/Doc/PreserveObjectReferences.html b/Doc/PreserveObjectReferences.html deleted file mode 100644 index 471ac68c..00000000 --- a/Doc/PreserveObjectReferences.html +++ /dev/null @@ -1,138 +0,0 @@ - - - - Serialization and Preserving Object References - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Serialization and Preserving Object References
- -
- - -

By default Json.NET will serialize all objects it encounters by value. If a list - contains two Person references, and both references point to the same object - then the JsonSerializer will write out all the names and values for each - reference.

- -
- -
-
Person p = new Person
-
  {
-
    BirthDate = new DateTime(1980, 12, 23, 0, 0, 0, DateTimeKind.Utc),
-
    LastModified = new DateTime(2009, 2, 20, 12, 59, 21, DateTimeKind.Utc),
-
    Name = "James"
-
  };
-
 
-
List<Person> people = new List<Person>();
-
people.Add(p);
-
people.Add(p);
-
 
-
string json = JsonConvert.SerializeObject(people, Formatting.Indented);
-
//[
-
//  {
-
//    "Name": "James",
-
//    "BirthDate": "\/Date(346377600000)\/",
-
//    "LastModified": "\/Date(1235134761000)\/"
-
//  },
-
//  {
-
//    "Name": "James",
-
//    "BirthDate": "\/Date(346377600000)\/",
-
//    "LastModified": "\/Date(1235134761000)\/"
-
//  }
-
//]
-
-
-

In most cases this is the desired result but in certain scenarios writing the second item in the list as a reference to the first is a better solution. - If the above JSON was deserialized now then the returned list would contain two - completely separate Person objects with the same values. Writing references by value will also cause problems on objects where a - circular reference occurs.

- -

PreserveReferencesHandling

-

Settings PreserveReferencesHandling will track object references when serializing - and deserializing JSON.

- -
-
-
string json = JsonConvert.SerializeObject(people, Formatting.Indented,
-
  new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
-
//[
-
//  {
-
//    "$id": "1",
-
//    "Name": "James",
-
//    "BirthDate": "\/Date(346377600000)\/",
-
//    "LastModified": "\/Date(1235134761000)\/"
-
//  },
-
//  {
-
//    "$ref": "1"
-
//  }
-
//]
-
 
-
List<Person> deserializedPeople = JsonConvert.DeserializeObject<List<Person>>(json,
-
  new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
-
 
-
Console.WriteLine(deserializedPeople.Count);
-
// 2
-
 
-
Person p1 = deserializedPeople[0];
-
Person p2 = deserializedPeople[1];
-
 
-
Console.WriteLine(p1.Name);
-
// James
-
Console.WriteLine(p2.Name);
-
// James
-
 
-
bool equal = Object.ReferenceEquals(p1, p2);
-
// true
-
-
- -

The first Person in the list is serizlied with the addition of an object Id. The - second Person in JSON is now only a reference to the first.

-

With PreserveReferencesHandling on now only one Person object is created on - deserialization and the list contains two references to it, mirroring what we - started with.

- -

IsReference on JsonObjectAttribute, JsonArrayAttribute and JsonPropertyAttribute

- - -

The PreserveReferencesHandling setting on the JsonSerializer will change - how all objects are serialized and deserialized. For fine grain control over which - objects and members should be serialized as a reference there is the IsReference property on - the JsonObjectAttribute, JsonArrayAttribute and JsonPropertyAttribute.

-

Setting IsReference on JsonObjectAttribute or JsonArrayAttribute to true will - mean the JsonSerializer will always serialize the type the attribute is against - as a reference. Setting IsReference on the JsonPropertyAttribute to true will - serialize only that property as a reference.

- -
- -
-
[JsonObject(IsReference = true)]
-
public class EmployeeReference
-
{
-
  public string Name { get; set; }
-
  public EmployeeReference Manager { get; set; }
-
}
-
- -
-

IReferenceResolver

-

To customize how references are generated and resolved the IReferenceResolver interface is available to inherit from and use with the JsonSerializer.

- - -
- - - - \ No newline at end of file diff --git a/Doc/ReadingWritingJSON.aml b/Doc/ReadingWritingJSON.aml new file mode 100644 index 00000000..605f368a --- /dev/null +++ b/Doc/ReadingWritingJSON.aml @@ -0,0 +1,37 @@ + + + + + To manually read and write JSON Json.NET provides the + T:Newtonsoft.Json.JsonReader + and + T:Newtonsoft.Json.JsonWriter classes. + +
+ JsonTextReader and JsonTextWriter + + T:Newtonsoft.Json.JsonTextReader + and T:Newtonsoft.Json.JsonTextWriter + are used to read and write JSON text. + The JsonTextWriter has a number of settings on it to control how JSON is formatted + when it is written. These options include formatting, indention character, indent + count and quote character. + + + +
+
+ JTokenReader and JTokenWriter + + T:Newtonsoft.Json.Linq.JTokenReader + and T:Newtonsoft.Json.Linq.JTokenWriter + read and write LINQ to JSON objects. They are located in the + N:Newtonsoft.Json.Linq + namespace. These objects allow you to use LINQ to JSON objects with objects that + read and write JSON such as the JsonSerializer. For example you can deserialize + from a LINQ to JSON object into a regular .NET object and vice versa. + + +
+
+
\ No newline at end of file diff --git a/Doc/ReadingWritingJSON.html b/Doc/ReadingWritingJSON.html deleted file mode 100644 index 207e1465..00000000 --- a/Doc/ReadingWritingJSON.html +++ /dev/null @@ -1,87 +0,0 @@ - - - - Reading and Writing JSON - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Reading and Writing JSON
- -
- - -

To manually read and write JSON Json.NET provides the JsonReader and JsonWriter classes.

- -

JsonTextReader and JsonTextWriter

-

JsonTextReader and JsonTextWriter are used to read and write JSON text. The JsonTextWriter has a number of settings on it to control how JSON is formatted when it is written. These options include formatting, indention character, indent count and quote character.

- -
- -
-
StringBuilder sb = new StringBuilder();
-
StringWriter sw = new StringWriter(sb);
-
 
-
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
-
{
-
  jsonWriter.Formatting = Formatting.Indented;
-
 
-
  jsonWriter.WriteStartObject();
-
  jsonWriter.WritePropertyName("CPU");
-
  jsonWriter.WriteValue("Intel");
-
  jsonWriter.WritePropertyName("PSU");
-
  jsonWriter.WriteValue("500W");
-
  jsonWriter.WritePropertyName("Drives");
-
  jsonWriter.WriteStartArray();
-
  jsonWriter.WriteValue("DVD read/writer");
-
  jsonWriter.WriteComment("(broken)");
-
  jsonWriter.WriteValue("500 gigabyte hard drive");
-
  jsonWriter.WriteValue("200 gigabype hard drive");
-
  jsonWriter.WriteEnd();
-
  jsonWriter.WriteEndObject();
-
}
-
 
-
// {
-
//   "CPU": "Intel",
-
//   "PSU": "500W",
-
//   "Drives": [
-
//     "DVD read/writer"
-
//     /*(broken)*/,
-
//     "500 gigabyte hard drive",
-
//     "200 gigabype hard drive"
-
//   ]
-
// }
-
- -
- -

JTokenReader and JTokenWriter

-

JTokenReader and JTokenWriter read and write LINQ to JSON objects. They are located in the Newtonsoft.Json.Linq namespace. These objects allow you to use LINQ to JSON objects with objects that read and write JSON such as the JsonSerializer. For example you can deserialize from a LINQ to JSON object into a regular .NET object and vice versa.

- -
- -
-
JObject o = new JObject(
-
  new JProperty("Name", "John Smith"),
-
  new JProperty("BirthDate", new DateTime(1983, 3, 20))
-
  );
-
 
-
JsonSerializer serializer = new JsonSerializer();
-
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));
-
 
-
Console.WriteLine(p.Name);
-
// John Smith
-
- -
- - -
- - - - \ No newline at end of file diff --git a/Doc/ReducingSerializedJSONSize.aml b/Doc/ReducingSerializedJSONSize.aml new file mode 100644 index 00000000..df4b60e7 --- /dev/null +++ b/Doc/ReducingSerializedJSONSize.aml @@ -0,0 +1,127 @@ + + + + + + + + One of the common problems encountered when serializing .NET objects to + JSON is that the JSON ends up containing a lot of unwanted properties and values. + This can be especially important when returning JSON to the client. More JSON + means more bandwidth and a slower website. + To solve the issue of unwanted JSON Json.NET has a range of built in + options to fine tune what gets written from a serialized object. + + +
+ JsonIgnoreAttribute and DataMemberAttribute + + + By default Json.NET will include all of a classes public properties and fields + in the JSON it creates. Adding the + T:Newtonsoft.Json.JsonIgnoreAttribute + to a property tells the serializer to always skip writing it to the JSON result. + + + + If a class has many properties and you only want to serialize a small subset + of them then adding JsonIgnore to all the others will be tedious and error prone. + The way to tackle this scenario is to add the + T:System.Runtime.Serialization.DataContractAttribute + to the class and + T:System.Runtime.Serialization.DataMemberAttributes + to the properties to serialize. This is opt-in + serialization, only the properties you mark up with be serialized, compared to + opt-out serialization using JsonIgnoreAttribute. + + + +
+
+ Formatting + + JSON written by the serializer with an option of + T:Newtonsoft.Json.Formatting + set to Indented produces + nicely formatted, easy to read JSON that is great for readability when you are + developing. Formatting.None on the other hand keeps the JSON result small, skipping + all unnecessary spaces and line breaks to produce the most compact and efficient + JSON possible. + +
+
+ NullValueHandling + + T:Newtonsoft.Json.NullValueHandling + is an option on the JsonSerializer and controls how the + serializer handles properties with a null value. By setting a value of + NullValueHandling.Ignore the JsonSerializer skips writing any properties that have + a value of null. + + + + + NullValueHandling can also be customized on individual properties + using the a + T:Newtonsoft.Json.JsonPropertyAttribute. + The JsonPropertyAttribute value of + NullValueHandling will override the setting on the JsonSerializer for that + property. + +
+
+ DefaultValueHandling + + T:Newtonsoft.Json.DefaultValueHandling + is an option on the JsonSerializer and controls how the serializer handles + properties with a default value. Setting a value of DefaultValueHandling.Ignore + will make the JsonSerializer skip writing any properties that have a default + value to the JSON result. For object references this will be null. For value + types like int and DateTime the serializer will skip the default unitialized + value for that value type. + + Json.NET also allows you to customize what the default value of an individual + property is using the + T:System.ComponentModel.DefaultValueAttribute. + For example if a string property called + Department always returns an empty string in its default state and you didn't want + that empty string in your JSON then placing the DefaultValueAttribute on Department + with that value will mean Department is no longer written to JSON unless it has a + value. + + + + + DefaultValueHandling can also be customized on individual properties using + the a + T:Newtonsoft.Json.JsonPropertyAttribute. + The JsonPropertyAttribute value of DefaultValueHandling + will override the setting on the JsonSerializer for that property. + +
+
+ IContractResolver + + For more flexibility the + T:Newtonsoft.Json.Serialization.IContractResolver + provides an interface to customize + almost every aspect of how a .NET object gets serialized to JSON, including changing + serialization behavior at runtime. + + + + + +
+
+
\ No newline at end of file diff --git a/Doc/ReducingSerializedJSONSize.html b/Doc/ReducingSerializedJSONSize.html deleted file mode 100644 index 64d002e9..00000000 --- a/Doc/ReducingSerializedJSONSize.html +++ /dev/null @@ -1,280 +0,0 @@ - - - - Reducing Serialized JSON Size - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Reducing Serialized JSON Size
- -
- -

One of the common problems encountered when serializing .NET objects to JSON is that the JSON ends up containing a lot of unwanted properties and values. This can be especially important when returning JSON to the client. More JSON means more bandwidth and a slower website.

- -

To solve the issue of unwanted JSON Json.NET has a range of built in options to fine tune what gets written from a serialized object.

- -

JsonIgnoreAttribute and DataMemberAttribute

-

By default Json.NET will include all of a classes public properties and fields in - the JSON it creates. Adding the JsonIgnoreAttribute to a property tells the serializer - to always skip writing it to the JSON result.

- -
-
-
-
public class Car
-
{
-
  // included in JSON
-
  public string Model { get; set; }
-
  public DateTime Year { get; set; }
-
  public List<string> Features { get; set; }
-
 
-
  // ignored
-
  [JsonIgnore]
-
  public DateTime LastModified { get; set; }
-
}
-
-
-
- -

If a class has many properties and you only want to serialize a small subset of - them then adding JsonIgnore to all the others will be tedious and error prone. - The way to tackle this scenario is to add the - DataContractAttribute to the class and - DataMemberAttributes to the properties to serialize. This is opt-in - serialization, only the properties you mark up with be serialized, compared to - opt-out serialization using JsonIgnoreAttribute.

- -
- -
-
-
[DataContract]
-
public class Computer
-
{
-
  // included in JSON
-
  [DataMember]
-
  public string Name { get; set; }
-
  [DataMember]
-
  public decimal SalePrice { get; set; }
-
 
-
  // ignored
-
  public string Manufacture { get; set; }
-
  public int StockCount { get; set; }
-
  public decimal WholeSalePrice { get; set; }
-
  public DateTime NextShipmentDate { get; set; }
-
}
-
-
-
- -

Formatting

- -

JSON written by the serializer with an option of Formatting.Indented produces nicely formatted, easy to read JSON – great when you are developing. Formatting.None on the other hand keeps the JSON result small, skipping all unnecessary spaces and line breaks to produce the most compact and efficient JSON possible.

- -

NullValueHandling

- -

NullValueHandling is an option on the JsonSerializer and controls how the serializer handles properties with a null value. By setting a value of NullValueHandling.Ignore the JsonSerializer skips writing any properties that have a value of null.

- -
-
-
-
public class Movie
-
{
-
  public string Name { get; set; }
-
  public string Description { get; set; }
-
  public string Classification { get; set; }
-
  public string Studio { get; set; }
-
  public DateTime? ReleaseDate { get; set; }
-
  public List<string> ReleaseCountries { get; set; }
-
}
-
-
-
- -
-
-
-
Movie movie = new Movie();
-
movie.Name = "Bad Boys III";
-
movie.Description = "It's no Bad Boys";
-
 
-
string included = JsonConvert.SerializeObject(movie,
-
  Formatting.Indented,
-
  new JsonSerializerSettings { });
-
 
-
// {
-
//   "Name": "Bad Boys III",
-
//   "Description": "It's no Bad Boys",
-
//   "Classification": null,
-
//   "Studio": null,
-
//   "ReleaseDate": null,
-
//   "ReleaseCountries": null
-
// }
-
 
-
string ignored = JsonConvert.SerializeObject(movie,
-
  Formatting.Indented,
-
  new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
-
 
-
// {
-
//   "Name": "Bad Boys III",
-
//   "Description": "It's no Bad Boys"
-
// }
-
-
-
- -

NullValueHandling can also be customized on individual properties using the a JsonPropertyAttribute. The JsonPropertyAttribute value of NullValueHandling will override the setting on the JsonSerializer for that property.

- -

DefaultValueHandling

- -

DefaultValueHandling is an option on the JsonSerializer and controls how the serializer handles properties with a default value. Setting a value of DefaultValueHandling.Ignore will make the JsonSerializer skip writing any properties that have a default value to the JSON result. For object references this will be null. For value types like int and DateTime the serializer will skip the default unitialized value for that value type.

- -

Json.NET also allows you to customize what the default value of an individual property is using the DefaultValueAttribute. For example if a string property called Department always returns an empty string in its default state and you didn't want that empty string in your JSON then placing the DefaultValueAttribute on Department with that value will mean Department is no longer written to JSON unless it has a value.

- -
-
-
-
public class Invoice
-
{
-
  public string Company { get; set; }
-
  public decimal Amount { get; set; }
-
 
-
  // false is default value of bool
-
  public bool Paid { get; set; }
-
  // null is default value of nullable
-
  public DateTime? PaidDate { get; set; }
-
 
-
  // customize default values
-
  [DefaultValue(30)]
-
  public int FollowUpDays { get; set; }
-
  [DefaultValue("")]
-
  public string FollowUpEmailAddress { get; set; }
-
}
-
-
-
- -
-
-
-
Invoice invoice = new Invoice
-
{
-
  Company = "Acme Ltd.",
-
  Amount = 50.0m,
-
  Paid = false,
-
  FollowUpDays = 30,
-
  FollowUpEmailAddress = string.Empty,
-
  PaidDate = null
-
};
-
 
-
string included = JsonConvert.SerializeObject(invoice,
-
  Formatting.Indented,
-
  new JsonSerializerSettings { });
-
 
-
// {
-
//   "Company": "Acme Ltd.",
-
//   "Amount": 50.0,
-
//   "Paid": false,
-
//   "PaidDate": null,
-
//   "FollowUpDays": 30,
-
//   "FollowUpEmailAddress": ""
-
// }
-
 
-
string ignored = JsonConvert.SerializeObject(invoice,
-
  Formatting.Indented,
-
  new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
-
 
-
// {
-
//   "Company": "Acme Ltd.",
-
//   "Amount": 50.0
-
// }
-
-
-
- -

DefaultValueHandling can also be customized on individual properties using the a JsonPropertyAttribute. The JsonPropertyAttribute value of DefaultValueHandling will override the setting on the JsonSerializer for that property.

- -

IContractResolver

- -

For more flexibility the IContractResolver provides an interface to customize almost every aspect of how a .NET object gets serialized to JSON, including changing serialization behavior at runtime.

- -
-
-
-
public class DynamicContractResolver : DefaultContractResolver
-
{
-
  private readonly char _startingWithChar;
-
  public DynamicContractResolver(char startingWithChar)
-
  {
-
    _startingWithChar = startingWithChar;
-
  }
-
 
-
  protected override IList<JsonProperty> CreateProperties(JsonObjectContract contract)
-
  {
-
    IList<JsonProperty> properties = base.CreateProperties(contract);
-
 
-
    // only serializer properties that start with the specified character
-
    properties = 
-
      properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
-
 
-
    return properties;
-
  }
-
}
-
 
-
public class Book
-
{
-
  public string BookName { get; set; }
-
  public decimal BookPrice { get; set; }
-
  public string AuthorName { get; set; }
-
  public int AuthorAge { get; set; }
-
  public string AuthorCountry { get; set; }
-
}
-
-
-
- -
-
-
-
Book book = new Book
-
              {
-
                BookName = "The Gathering Storm",
-
                BookPrice = 16.19m,
-
                AuthorName = "Brandon Sanderson",
-
                AuthorAge = 34,
-
                AuthorCountry = "United States of America"
-
              };
-
 
-
string startingWithA = JsonConvert.SerializeObject(book, Formatting.Indented,
-
  new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') });
-
 
-
// {
-
//   "AuthorName": "Brandon Sanderson",
-
//   "AuthorAge": 34,
-
//   "AuthorCountry": "United States of America"
-
// }
-
 
-
string startingWithB = JsonConvert.SerializeObject(book, Formatting.Indented,
-
  new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') });
-
 
-
// {
-
//   "BookName": "The Gathering Storm",
-
//   "BookPrice": 16.19
-
// }
-
-
-
- - - -
- - - - \ No newline at end of file diff --git a/Doc/SelectToken.aml b/Doc/SelectToken.aml new file mode 100644 index 00000000..f9396b2c --- /dev/null +++ b/Doc/SelectToken.aml @@ -0,0 +1,37 @@ + + + + + + Overload:Newtonsoft.Json.Linq.JToken.SelectToken + provides a method to query LINQ to JSON using a single string path to a desired + T:Newtonsoft.Json.Linq.JToken. + SelectToken makes dynamic queries easy because the entire query is defined in a string. + +
+ SelectToken + + + SelectToken is a method on JToken and takes a string path to a child token. + SelectToken returns the child token or a null reference if a token couldn't be + found at the path's location. + The path is made up of property names and array indexes separated by periods. + Array indexes can use either square or round brackets. Both of the following are + valid paths and are equivalent to each other: Manufacturers[0].Name + and Manufacturers(0).Name. + + + +
+
+ SelectToken with LINQ + + + SelectToken can be used in combination with standard LINQ methods. + + +
+
+
\ No newline at end of file diff --git a/Doc/SelectToken.html b/Doc/SelectToken.html deleted file mode 100644 index 14ecc5ae..00000000 --- a/Doc/SelectToken.html +++ /dev/null @@ -1,116 +0,0 @@ - - - - Querying LINQ to JSON with SelectToken - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Querying LINQ to JSON with SelectToken
- -
- -

SelectToken provides a method to query LINQ to JSON using a single string path to a - desired JToken. SelectToken makes dynamic queries - easy because the entire - query is defined in a string.

- -
-
-
-
string name = (string)o.SelectToken("Manufacturers[0].Name");
- -
-
-
- -

SelectToken

-

SelectToken is a method on JToken and takes a string path to a child token. - SelectToken returns the child token or a null reference if a token couldn't be - found at the path's location.

-

The - path is made up of property names and array indexes separated by periods. Array indexes - can use either square or round brackets. Both - of the following are valid paths and are equivalent to each other: Manufacturers[0].Name - and Manufacturers(0).Name.

- -
-
-
-
JObject o = JObject.Parse(@"{
-
  ""Stores"": [
-
    ""Lambton Quay"",
-
    ""Willis Street""
-
  ],
-
  ""Manufacturers"": [
-
    {
-
      ""Name"": ""Acme Co"",
-
      ""Products"": [
-
        {
-
          ""Name"": ""Anvil"",
-
          ""Price"": 50
-
        }
-
      ]
-
    },
-
    {
-
      ""Name"": ""Contoso"",
-
      ""Products"": [
-
        {
-
          ""Name"": ""Elbow Grease"",
-
          ""Price"": 99.95
-
        },
-
        {
-
          ""Name"": ""Headlight Fluid"",
-
          ""Price"": 4
-
        }
-
      ]
-
    }
-
  ]
-
}");
-
 
-
string name = (string)o.SelectToken("Manufacturers[0].Name");
-
// Acme Co
-
 
-
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
-
// 50
-
 
-
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
-
// Elbow Grease
-
-
-
- -

SelectToken with LINQ

- -

SelectToken can be used in combination with standard LINQ methods.

- -
- -
- -
-
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
-
// Lambton Quay
-
// Willis Street
-
 
-
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
-
// null
-
// Headlight Fluid
-
 
-
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
-
// 149.95
-
- -
-
- - -
- - - - \ No newline at end of file diff --git a/Doc/SerializationAttributes.aml b/Doc/SerializationAttributes.aml new file mode 100644 index 00000000..89e6361b --- /dev/null +++ b/Doc/SerializationAttributes.aml @@ -0,0 +1,138 @@ + + + + + + + + Attributes can be used to control how Json.NET serializes and deserializes .NET objects. + + + T:Newtonsoft.Json.JsonObjectAttribute - Placed on classes to control how it should be serialized as a JSON object. + T:Newtonsoft.Json.JsonArrayAttribute - Placed on collections to control how it should be serialized as a JSON array. + T:Newtonsoft.Json.JsonDictionaryAttribute - Placed on dictionaries to control how it should be serialized as a JSON object. + T:Newtonsoft.Json.JsonPropertyAttribute - Placed on fields and properties to control how it should be serialized as a property in a JSON object. + T:Newtonsoft.Json.JsonConverterAttribute - Placed on either classes or fields and properties to specify which JsonConverter should be used during serialization. + + + + +
+ Standard .NET Serialization Attributes + + + As well as using the built-in Json.NET attributes, Json.NET also looks for the T:System.SerializableAttribute + (if IgnoreSerializableAttribute on DefaultContractResolver is set to false) + T:System.Runtime.Serialization.DataContractAttribute, + T:System.Runtime.Serialization.DataMemberAttribute + and T:System.NonSerializedAttribute and attributes when determining how JSON is to be serialized and deserialized. + + + + + Json.NET attributes take presidence over standard .NET serialization attributes, e.g. if both JsonPropertyAttribute + and DataMemberAttribute are present on a property and both customize the name, + the name from JsonPropertyAttribute will be used. + + + + + +
+ +
+ Json.NET Serialization Attributes + +
+ JsonObjectAttribute + + + The MemberSerialization flag on this attribute specifies whether member serialization is opt-in + (a member must have the JsonProperty or DataMember attribute to be serialized), opt-out (everything is + serialized by default but can be ignored with the JsonIgnoreAttribute, Json.NET's default behavor) or + fields (all public and private fields are serialized, properties are ignored). + Json.NET serializes .NET classes that implement IEnumerable as an JSON array populated with the + IEnumerable values. Placing the JsonPropertyAttribute overrides this behavor and forces the serializer + to serialize the class's fields and properties. + The DataContractAttribute can be used as substitute for JsonObjectAttribute. The + DataContractAttribute will default member serialization to opt-in. + +
+ +
+ JsonArrayAttribute/JsonDictionaryAttribute + + + The JsonArrayAttribute and JsonDictionaryAttributes are used to specified whether a class is serialized as that collection type. + The collection attributes have options to customize the JsonConverter, type name handling and reference handling that are applied to collection items. + +
+ +
+ JsonPropertyAttribute + + + JsonPropertyAttribute has a number of uses: + + + By default the JSON property will have the same name as the .NET property. This attribute allows the name to be customized. + Indicates that a property should be serialized when member serialization is set to opt-in. + Includes non-public properties in serialization and deserialization. + Customize type name, reference, null and default value handling for the property value. + Customize the property's collection items JsonConverter, type name handing and reference handling. + + + The DataMemberAttribute can be used as substitute for JsonPropertyAttribute. + + +
+ +
+ JsonIgnoreAttribute + + + Excludes a field or property from serialization. + The T:System.NonSerializedAttribute can be used as substitute for JsonIgnoreAttribute. + +
+ +
+ JsonConverterAttribute + + + The JsonConverterAttribute specifies which JsonSerializer is used to convert an object. + The attribute can be placed on a class or a member. When placed on a class the JsonConverter + specified by the attribute will be the default way of serializing that class. When the attribute is + on a field or property then the specified JsonConverter will always be used to serialize that value. + The priority of which JsonConverter is used is member attribute then class attribute and finally + any converters passed to the JsonSerializer. + + + + This example shows the JsonConverterAttribute being applied to a property. + + + + To apply a JsonConverter to the items in a collection use either T:Newtonsoft.Json.JsonArrayAttribute, + T:Newtonsoft.Json.JsonDictionaryAttribute or + T:Newtonsoft.Json.JsonPropertyAttribute + and set the ItemConverterType property to the converter type you want to use. + +
+
+
+
+
\ No newline at end of file diff --git a/Doc/SerializationAttributes.html b/Doc/SerializationAttributes.html deleted file mode 100644 index 03b55bc2..00000000 --- a/Doc/SerializationAttributes.html +++ /dev/null @@ -1,153 +0,0 @@ - - - - Serialization Attributes - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Serialization Attributes
- -
- - -

Attributes can be used to control how Json.NET serializes and deserializes .NET objects.

-
    -
  • JsonObjectAttribute - Placed on classes to control how it should be serialized as a JSON object.
  • -
  • JsonArrayAttribute - Placed on collections to control how it should be serialized as a JSON array.
  • -
  • JsonDictionaryAttribute - Placed on - dictionaries to control how it should be serialized as a JSON object.
  • -
  • JsonPropertyAttribute - Placed on fields and properties to control how it should be serialized as a property in a JSON object.
  • -
  • JsonConverterAttribute - Placed on either classes or fields and properties to specify which JsonConverter should be used during serialization.
  • -
-

As well as using the built-in Json.NET attributes, Json.NET also looks for the - - Serializable (if IgnoreSerializableAttribute on DefaultContractResolver is - set to false) - DataContract, - DataMember - and - - NotSerialized and - attributes when determining how JSON is to be serialized and deserialized. If both are present the Json.NET serialization attributes take precedence.

- -
- -
-
[JsonObject(MemberSerialization.OptIn)]
-
public class Person
-
{
-
  // "John Smith"
-
  [JsonProperty]
-
  public string Name { get; set; }
-
 
-
  // "2000-12-15T22:11:03"
-
  [JsonProperty]
-
  public DateTime BirthDate { get; set; }
-
 
-
  // new Date(976918263055)
-
  [JsonProperty]
-
  [JsonConverter(typeof(JavaScriptDateTimeConverter))]
-
  public DateTime LastModified { get; set; }
-
 
-
  // not serialized because mode is opt-in
-
  public string Department { get; set; }
-
}
-
- -
- -
JsonObjectAttribute
-

The MemberSerialization flag on this attribute specifies whether member serialization is opt-in (a member must have the JsonProperty or DataMember attribute to be serialized), opt-out (everything is serialized by default but can be ignored with the JsonIgnoreAttribute, - Json.NET's default behavor) or fields (all public and private fields are - serialized, properties are ignored).

-

Json.NET serializes .NET classes that implement IEnumerable as an - JSON array populated with the IEnumerable values. Placing the JsonPropertyAttribute overrides this - behavor and forces the serializer to serialize the class's fields and properties.

-

The DataContractAttribute can be used as substitute for JsonObjectAttribute. - The DataContractAttribute will default member serialization to opt-in.

- -
JsonArrayAttribute/JsonDictionaryAttribute
-

The JsonArrayAttribute and JsonDictionaryAttributes are used to specified - whether a class is serialized as that collection type.

-

The collection attributes have options to customize the JsonConverter, type name handling - and reference handling that are applied to collection items.

-
JsonPropertyAttribute
-

JsonPropertyAttribute has a number of uses:

-
    -
  • By default the JSON property will have the same name as the .NET property. This attribute allows the name to be customized.
  • -
  • Indicates that a property should be serialized when member serialization is set to opt-in.
  • -
  • Includes non-public properties in serialization and deserialization.
  • -
  • Customize type name, reference, null and default value handling for the - property value.
  • -
  • Customize the property's collection items JsonConverter, type name handing and - reference handling.
  • -
-

- The DataMemberAttribute can be used as substitute for JsonPropertyAttribute.

-
JsonIgnoreAttribute
-

Excludes a field or property from serialization.

-

The NotSerializedAttribute can be used as substitute for JsonIgnoreAttribute.

-
JsonConverterAttribute
-

The JsonConverterAttribute specifies which JsonSerializer is used to convert an object.

-

The attribute can be placed on a class or a member. When placed on a class the JsonConverter - specified by the attribute will be the default way of serializing that class. When the attribute is on a field -or property then the specified JsonConverter will always be used to serialize that value.

-

The priority of which JsonConverter is used is member attribute then class attribute and -finally any converters passed to the JsonSerializer.

- -
-
-
public class MemberConverterClass
-
{
-
  public DateTime DefaultConverter { get; set; }
-
  [JsonConverter(typeof(IsoDateTimeConverter))]
-
  public DateTime MemberConverter { get; set; }
-
}
-
-
-

This example shows the JsonConverterAttribute being applied to a property.

- - -
-
-
DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
-
 
-
MemberConverterClass c = new MemberConverterClass
-
  {
-
    DefaultConverter = date,
-
    MemberConverter = date
-
  };
-
 
-
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
-
 
-
Console.WriteLine(json);
-
//{
-
//  "DefaultConverter": "\/Date(0)\/",
-
//  "MemberConverter": "1970-01-01T00:00:00Z"
-
//}
-
- -
- -

To apply a JsonConverter to the items in a collection use either - JsonArrayAttribute, - - JsonDictionaryAttribute or - JsonPropertyAttribute and set - the ItemConverterType property to the converter type you want to use.

- - -
- - - - \ No newline at end of file diff --git a/Doc/SerializationCallbacks.aml b/Doc/SerializationCallbacks.aml new file mode 100644 index 00000000..6e7b917c --- /dev/null +++ b/Doc/SerializationCallbacks.aml @@ -0,0 +1,68 @@ + + + + + + + + Json.NET supports serialization callback methods. A callback can be used to manipulate an object before and after its serialization and deserialization by the JsonSerializer. + + + OnSerializing + OnSerialized + OnDeserializing + OnDeserialized + + +To tell the serializer which methods should be called during the object's +serialization lifecycle, decorate a method with the appropraite attribute +(T:System.Runtime.Serialization.OnSerializingAttribute, +T:System.Runtime.Serialization.OnSerializedAttribute, +T:System.Runtime.Serialization.OnDeserializingAttribute, +T:System.Runtime.Serialization.OnDeserializedAttribute). + + + + +
+ Example + + + Example object with serialization callback methods: + + + + The example object being serialized and deserialized by Json.NET: + + + + + +
+
+
\ No newline at end of file diff --git a/Doc/SerializationCallbacks.html b/Doc/SerializationCallbacks.html deleted file mode 100644 index 11fd37c1..00000000 --- a/Doc/SerializationCallbacks.html +++ /dev/null @@ -1,143 +0,0 @@ - - - - Serialization Callbacks - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Serialization Callbacks
- -
- - -

Json.NET supports serialization callback methods. A callback can be used to - manipulate an object before and after its serialization and deserialization by - the JsonSerializer.

-
    -
  • OnSerializing
  • -
  • OnSerialized
  • -
  • OnDeserializing
  • -
  • OnDeserialized
  • -
-

To tell the serializer which methods should be called during the object's serialization - lifecycle, decorate a method with the appropraite attribute (OnSerializingAttribute, - OnSerializedAttribute, - OnDeserializingAttribute, - OnDeserializedAttribute).

-

Example object with serialization callback methods:

- -
-
-
public class SerializationEventTestObject
-
{
-
  // 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.";
-
  }
-
}
-
-
- -

The example object being serialized and deserialized by Json.NET:

- -
-
-
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.
-
-
- - - -
- - - - \ No newline at end of file diff --git a/Doc/SerializationErrorHandling.aml b/Doc/SerializationErrorHandling.aml new file mode 100644 index 00000000..cc09f47e --- /dev/null +++ b/Doc/SerializationErrorHandling.aml @@ -0,0 +1,98 @@ + + + + + + + + Json.NET supports error handling during serialization and + deserialization. Error handling lets you catch an error and + choose whether to handle it and continue with serialization or + let the error bubble up and be thrown in your application. + Error handling is defined through two methods: the Error event on + JsonSerializer and the OnErrorAttribute. + + +
+ Error Event + + + The E:Newtonsoft.Json.JsonSerializer.Error + event is an event handler found on T:Newtonsoft.Json.JsonSerializer. + The error event is raised whenever an exception is thrown while serializing + or deserialing JSON. Like all settings found on JsonSerializer it can also + be set on T:Newtonsoft.Json.JsonSerializerSettings + and passed to the serialization methods on JsonConvert. + + + + In this example we are deserializing a JSON array to a collection + of DateTimes. On the JsonSerializerSettings a handler has been assigned + to the Error event which will log the error message and mark the error + as handled. + + The result of deserializing the JSON is three successfully deserialized + dates and three error messages: one for the badly formatted string, "I am + not a date and will error!", one for the nested JSON array and one for the + null value since the list doesn't allow nullable DateTimes. The event + handler has logged these messages and Json.NET has continued on deserializing + the JSON because the errors were marked as handled. + + One thing to note with error handling in Json.NET is that an + unhandled error will bubble up and raise the event on each of its + parents, e.g. an unhandled error when serializing a collection of objects + will be raised twice, once against the object and then again on the collection. + This will let you handle an error either where it occurred or on one of its + parents. + + + + If you aren't immediately handling an error and only want to + perform an action against it once then you can check to see whether the + T:Newtonsoft.Json.Serialization.ErrorEventArgs's + CurrentObject is equal to the OriginalObject. + OriginalObject is the object that threw the error and CurrentObject is + the object that the event is being raised against. They will only equal + the first time the event is raised against the OriginalObject. + +
+ +
+ OnErrorAttribute + + + The T:Newtonsoft.Json.Serialization.OnErrorAttribute + works much like the other +.NET serialization attributes +SerializationAttributes.htm +_self + + that Json.NET supports. To use it you simply place the + attribute on a method which takes the correct parameters: a + StreamingContext and a ErrorContext. The name of the method doesn't + matter. + + + + In this example accessing the the Roles property will throw an + exception when no roles have been set. The HandleError method will set + the error when serializing Roles as handled and allow Json.NET to + continue serializing the class. + + + + +
+
+
\ No newline at end of file diff --git a/Doc/SerializationErrorHandling.html b/Doc/SerializationErrorHandling.html deleted file mode 100644 index 5a507308..00000000 --- a/Doc/SerializationErrorHandling.html +++ /dev/null @@ -1,172 +0,0 @@ - - - - Serialization Error Handling - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Serialization Error Handling
- -
- - -

Json.NET supports error handling during serialization and deserialization. Error handling lets - you catch an error and choose whether to handle it and continue with serialization or let the error - bubble up and be thrown in your application.

-

Error handling is defined through two methods: - the Error event on JsonSerializer and the OnErrorAttribute.

-

Error Event

- -

- The Error event is an event handler found on JsonSerializer. The error event is raised whenever an - exception is thrown while serializing or deserialing JSON. Like all settings found on JsonSerializer - it can also be set on JsonSerializerSettings and passed to the serialization methods on JsonConvert.

- -
-
-
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.
-
-
-
-

- In this example we are deserializing a JSON array to a collection of DateTimes. On the JsonSerializerSettings - a handler has been assigned to the Error event which will log the error message and mark the error as handled. -

-

- The result of deserializing the JSON is three successfully deserialized dates and three error messages: - one for the badly formatted string, "I am not a date and will error!", one for the nested JSON array and one - for the null value since the list doesn't allow nullable DateTimes. The event handler has logged these messages - and Json.NET has continued on deserializing the JSON because the errors were marked as handled. -

-

- One thing to note with error handling in Json.NET is that an unhandled error will bubble up and raise the event - on each of its parents, e.g. an unhandled error when serializing a collection of objects will be raised twice, - once against the object and then again on the collection. This will let you handle an error either where it - occurred or on one of its parents. -

- - -
-
-
JsonSerializer serializer = new JsonSerializer();
-
serializer.Error += delegate(object sender, ErrorEventArgs args)
-
  {
-
    // only log an error once
-
    if (args.CurrentObject == args.ErrorContext.OriginalObject)
-
      errors.Add(args.ErrorContext.Error.Message);
-
  };
-
-
- -

If you aren't immediately handling an error and only want to perform an action against it once then -you can check to see whether the ErrorEventArg's CurrentObject is equal to the OriginalObject. -OriginalObject is the object that threw the error and CurrentObject is the object that the event is being raised -against. They will only equal the first time the event is raised against the OriginalObject.

- -

OnErrorAttribute

- -

- The OnErrorAttribute works much like the other .NET serialization attributes that Json.NET supports. - To use it you simply place the attribute on a method which takes the correct parameters: a StreamingContext and a ErrorContext. - The name of the method doesn't matter.

-
- -
-
public class PersonError
-
{
-
  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;
-
  }
-
}
-
-
-

- In this example accessing the the Roles property will throw an exception when no roles have - been set. The HandleError method will set the error when serializing Roles as handled and allow Json.NET to continue - serializing the class. -

- -
-
-
PersonError person = new PersonError
-
  {
-
    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"
-
//}
-
-
- - - -
- - - - \ No newline at end of file diff --git a/Doc/SerializationGuide.aml b/Doc/SerializationGuide.aml new file mode 100644 index 00000000..004fa430 --- /dev/null +++ b/Doc/SerializationGuide.aml @@ -0,0 +1,288 @@ + + + + + + + + The Json.NET serializer can serialize a wide variety of .NET objects. This guide looks at how it works, first at a high level and then in more detail. + + +
+ Summary + + + At a high level, the Json.NET serializer will convert primitive .NET values into primitive JSON values, + .NET arrays and collections to JSON arrays and everything else to JSON objects. + Json.NET will throw an error if it encounters incorrect JSON when deserializing a value. For example if + the serializer encounters a JSON property with an array of values and the type of matching .NET property is not + a collection then an error will be thrown, and vice-versa. + +
+
+ Complex Types + + + + + .NET + JSON + + + + IList, IEnumerable, IList<T>, Array + Array + + + IDictionary, IDictionary<TKey, TValue> + Object + + + Object (more detail below) + Object + +
+
+
+
+ Primitive Types + + + + + .NET + JSON + + + + String + String + + + Byte +SByte +UInt16 +Int16 +UInt32 +Int32 +UInt64 +Int64 + Integer + + + + Float + Double + Decimal + + Float + + + + Enum + + Integer (can be the enum value name with T:Newtonsoft.Json.Converters.StringEnumConverter) + + + + DateTime + + String ( +Serializing Dates in JSON +DatesInJSON.htm +_self +) + + + + Byte[] + + String (base 64 encoded) + + + + Type + + String (type name) + + + + Guid + + String + + + + T:System.ComponentModel.TypeConverter (convertible to String) + + String + +
+
+
+ +
+ Breakdown of Type Serialization + + + + +
+ Objects + + + .NET types that don't fall into any other category listed below + (i.e. aren't lists, dictionaries, dynamic, implement ISerializable, etc) + are serialized as JSON objects. + By default types are serialized in opt-out mode. What that means is all public fields and properties with + getters are automatically serialized to JSON and members that shouldn't be serialized are opted-out using the + JsonIgnoreAttribute. To serialize private members the JsonPropertyAttribute can be placed on private fields and + properties or the DefaultMembersSearchFlags can be changed on DefaultContractResolver to change how members are + serialized on all types. + Types can also be serialized using opt-in mode. Only properties and fields that have a JsonPropertyAttribute + or DataMemberAttribute on them will be serialized. Opt-in mode for an object is specified using the JsonObjectAttribute + on the class. + Finally types can be serialized using a fields mode. All fields, both public and private, are serialized + and properties are ignored. This can be specified by setting MemberSerialization.Fields on a type with the JsonObject + attribute or by the .NET T:System.SerializableAttribute + and setting IgnoreSerializableAttribute on DefaultContractResolver to false. + +
+ +
+ IEnumerable, Lists and Arrays + + + .NET lists (types that inherit from IEnumerable) and .NET arrays are converted to JSON arrays. Because JSON + arrays only support a range of values and not properties, any additional properties and fields declared on .NET + collections are not serialized. In situations where a JSON array is not wanted the JsonObjectAttribute can be placed + on a .NET type that implements IEnumerable to force the type to be serialized as a JSON object instead. + JsonArrayAttribute has options on it to customize the JsonConverter, type name handling and reference handling + that are applied to collection items. + Note that if TypeNameHandling or PreserveReferencesHandling has been enabled for JSON arrays on the serializer + then JSON arrays are wrapped it a containing object. The object will have the type name/reference properties and a + $values property which will have the collection data. + When deserializing if a member is typed as the interface IList<T> then it will be deserialized as a + List<T>. + Read more about serializing collections here: +Serializing Collections +SerializingCollections.htm +_self + + +
+ +
+ Dictionarys and Hashtables + + + .NET dictionaries (types that inherit from IDictionary) are converted to JSON objects. Note that only the + dictionary name/values will be written to the JSON object when serializing and properties on the JSON object will + be added to the dictionary's name/values when deserializing. Additional members on the .NET dictionary are ignored + during serialization. + JsonDictionaryAttribute has options on it to customize the JsonConverter, type name handling and reference + handling that are applied to collection items. + When deserializing if a member is typed as the interface IDictionary<TKey, TValue> then it will be + deserialized as a Dictionary<TKey, TValue>. + Read more about serializing collections here: +Serializing Collections +SerializingCollections.htm +_self + + +
+ +
+ Untyped Objects + + + .NET properties on a class that don't specify a type (i.e. they are just object) are serialized as usual. When + untyped properties are deserialized the serializer has no way to know what type to create (unless type name handling + is enabled and the JSON contains the type names). + For these untyped properties the Json.NET serializer will read the JSON into LINQ to JSON objects and set them + to the property. JObject will be created for JSON objects, JArray will be created for JSON arrays and JValue for + primitive JSON values. + +
+ +
+ Dynamic + + + There are two different usages of dynamic (introduced in .NET 4) in .NET. The first are .NET properties with a + type of dynamic. Dynamic proeprties behave like properties declared as object, any value can be assigned to it, but + the difference being that properties and methods can be called on a dynamic property without casting. In Json.NET + dynamic properties are serialized and deserialized exactly the same as untyped objects: because dynamic isn't an actual + type Json.NET falls back to deserializing the JSON as LINQ to JSON objects. + The second usage of dynamic in .NET are classes that implement + T:System.Dynamic.IDynamicMetaObjectProvider. This interface lets + the implementor create dynamic objects that intercept the property and method calls on an object and use them. + T:System.Dynamic.ExpandoObject + is a good example of a dynamic object. + Dynamic objects are serialized as JSON objects. A property is written for every member name returned by + M:System.Dynamic.DynamicMetaObject.GetDynamicMemberNames. + When deserializing dynamic objects the serializer first attempts to set JSON property values on a normal .NET + member with the matching name. If no .NET member is found with the property name then the serializer will call + SetMember on the dynamic object. Because there is no type information for dynamic members on a dynamic object the + values assigned to them will be LINQ to JSON objects. + +
+ +
+ ISerializable + + + Types that implement ISerializable are serialized as JSON objects. When serializing only the values returned from + ISerializable.GetObjectData are used; members on the type are ignored. When deserializing the constructor with a + SerializationInfo and StreamingContext is called, passing the JSON object's values. + In situations where this behavior is not wanted the JsonObjectAttribute can be placed on a .NET type that + implements ISerializable to force it to be serialized as a normal JSON object. + +
+ +
+ LINQ to JSON + + + LINQ to JSON types (e.g. JObject, JArray) are automatically serialized and deserialized to their equivalent JSON + when encountered by the Json.NET serializer. + +
+ +
+ JsonConverter + + + Serialization of values that are convertible by a JsonConverter (i.e. CanConvert returns true for its type) is + completely overridden by the JsonConverter. The test to see whether a value can be converted by a JsonSerializer takes + precedence over all other tests. + JsonConverters can be defined and specified in a number of places: in an attribute on a member, in an attribute + on a class and added to the JsonSerializer's converters collection. The priority of which JsonConverter is used is the + JsonConverter defined by attribute on a member then the JsonConverter defined by an attribute on a class and finally + any converters passed to the JsonSerializer. + +
+ +
+
+ +
+
\ No newline at end of file diff --git a/Doc/SerializationGuide.html b/Doc/SerializationGuide.html deleted file mode 100644 index a1f14652..00000000 --- a/Doc/SerializationGuide.html +++ /dev/null @@ -1,346 +0,0 @@ - - - Serialization Guide - - - - -
- Json.NET - Quick Starts & API Documentation
- Serialization Guide
-
- -

- The Json.NET serializer can serialize a wide variety of .NET objects. This guide - looks at how it works at a high level and in more detail.

-

- Summary

-

- At a high level, the Json.NET serializer will convert primitive .NET values into - primitive JSON values, .NET arrays and collections to JSON arrays and everything - else to JSON objects.

-

- Json.NET will throw an error if it encounters incorrect JSON when deserializing - a value. For example if the serializer encounters a JSON property with an array - of values and the type of matching .NET property is not a collection then an error - will be thrown, and vice-versa. -

-

- Complex Types

- - - - - - - - - - - - - - - - - - - -
- .NET - - JSON -
- IList, IEnumerable, IList<T>, Array - -
- Array -
-
-
- IDictionary, IDictionary<TKey, TValue> - -
- Object -
-
-
- Object (more detail below) - -
- Object -
-
-
-

- Primitive Types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- .NET - - JSON -
- String - -
- String -
-
-
- Byte
- SByte
- UInt16
- Int16
- UInt32
- Int32
- UInt64
- Int64
-
-
-
-
- Integer -
-
-
- Float
- Double
- Decimal
-
-
-
-
- Float -
-
-
- Enum - -
- Integer (can be string with - StringEnumConverter) -
-
-
- DateTime - - -
-
- Byte[] - -
- String (base 64 encoded) -
-
-
- Type - -
- String (type name) -
-
-
- Guid - -
- String -
-
-
- TypeConverter (convertible to String) - -
- String -
-
-
-

- Breakdown of Type Serialization

-

- Objects

-

- .NET types that don't fall into any other category listed below (i.e. aren't lists, - dictionaries, dynamic, implement ISerializable, etc) are serialized as JSON objects.

-

- By default types are serialized in opt-out mode. What that means is all public fields - and properties with getters are automatically serialized to JSON and members that - shouldn't be serialized are opted-out using the JsonIgnoreAttribute. To serialize - private members the JsonPropertyAttribute can be placed on private fields and properties - or the DefaultMembersSearchFlags can be changed on DefaultContractResolver to change - how members are serialized on all types.

-

- Types can also be serialized using opt-in mode. Only - properties and fields that have a JsonPropertyAttribute - or DataMemberAttribute on them will be serialized. Opt-in mode for an object is - specified using the JsonObjectAttribute on the class. -

-

- Finally types can be serialized using a fields mode. All fields, both public and - private, are serialized and properties are ignored. This can be specified by - setting MemberSerialization.Fields on a type with the JsonObject attribute or by the .NET - - Serializable attribute and setting IgnoreSerializableAttribute on - DefaultContractResolver to false.

-

- IEnumerable, Lists and Arrayss

-

- .NET lists (types that inherit from IEnumerable) and .NET arrays are converted to - JSON arrays. Because JSON arrays only support a range of values and not properties, - any additional properties and fields declared on .NET collections are not serialized. - In situations where a JSON array is not wanted the JsonObjectAttribute can be placed - on a .NET type that implements IEnumerable to force the type to be serialized as - a JSON object instead.

-

- JsonArrayAttribute has options on it to customize the JsonConverter, type name handling - and reference handling that are applied to collection items.

-

- Note that if TypeNameHandling or PreserveReferencesHandling has been enabled for - JSON arrays on the serializer then JSON arrays are wrapped it a containing object. - The object will have the type name/reference properties and a $values property which - will have the collection data.

-

- When deserializing if a member is typed as the interface IList<T> then it - will be deserialized as a List<T>.

-

- Read more about serializing collections here: - Serializing Collections -

-

- Dictionarys and Hashtables

-

- .NET dictionaries (types that inherit from IDictionary) are converted to JSON objects. - Note that only the dictionary name/values will be written to the JSON object when - serializing and properties on the JSON object will be added to the dictionary's - name/values when deserializing. Additional members on the .NET dictionary are ignored - during serialization.

-

- JsonDictionaryAttribute has options on it to customize the JsonConverter, type name handling - and reference handling that are applied to collection items.

-

- When deserializing if a member is typed as the interface IDictionary<TKey, TValue> - then it will be deserialized as a Dictionary<TKey, TValue>.

-

- Read more about serializing collections here: - Serializing Collections

-

- Untyped Objects

-

- .NET properties on a class that don't specify a type (i.e. they are just object) - are serialized as usual. When untyped properties are deserialized the serializer - has no way to know what type to create (unless type name handling is enabled and - the JSON contains the type names).

-

- For these untyped properties the Json.NET serializer will read the JSON into LINQ - to JSON objects and set them to the property. JObject will be created for JSON objects, - JArray will be created for JSON arrays and JValue for primitive JSON values. -

-

- Dynamic

-

- There are two different usages of dynamic (introduced in .NET 4) in .NET. The first - are .NET properties with a type of dynamic. Dynamic proeprties behave like properties - declared as object, any value can be assigned to it, but the difference being that - properties and methods can be called on a dynamic property without casting. In Json.NET - dynamic properties are serialized and deserialized exactly the same as untyped objects: - because dynamic isn't an actual type Json.NET falls back to deserializing the JSON - as LINQ to JSON objects. -

-

- The second usage of dynamic in .NET are classes that implement IDynamicMetaObjectProvider. This interface lets the implementor - create dynamic objects that intercept the property and method calls on an object - and use them. ExpandoObject is a good example of a dynamic object. -

-

- Dynamic objects are serialized as JSON objects. A property is written for every - member name returned by DynamicMetaObject.GetDynamicMemberNames.

-

- When deserializing dynamic objects the serializer first attempts to set JSON property - values on a normal .NET member with the matching name. If no .NET member is found - with the property name then the serializer will call SetMember on the dynamic object. - Because there is no type information for dynamic members on a dynamic object the - values assigned to them will be LINQ to JSON objects

-

- ISerializable

-

- Types that implement ISerializable are serialized as JSON objects. When serializing - only the values returned from ISerializable.GetObjectData are used; members on the - type are ignored. When deserializing the constructor with a SerializationInfo and - StreamingContext is called, passing the JSON object's values.

-

- In situations where this behavior is not wanted the JsonObjectAttribute can be placed - on a .NET type that implements ISerializable to force it to be serialized as a normal - JSON object. -

-

- LINQ to JSON

-

- LINQ to JSON types (e.g. JObject, JArray) are automatically serialized and deserialized - to their equivalent JSON when encountered by the Json.NET serializer. -

-

- JsonConverter

-

- Serialization of values that are convertible by a JsonConverter (i.e. CanConvert - returns true for its type) is completely overridden by the JsonConverter. The test - to see whether a value can be converted by a JsonSerializer takes precedence over - all other tests.

-

- JsonConverters can be defined and specified in a number of places: in an attribute - on a member, in an attribute on a class and added to the JsonSerializer's converters - collection. The priority of which JsonConverter is used is the JsonConverter defined - by attribute on a member then the JsonConverter defined by an attribute on a class - and finally any converters passed to the JsonSerializer.

- -
- - diff --git a/Doc/SerializationSettings.aml b/Doc/SerializationSettings.aml new file mode 100644 index 00000000..527c536f --- /dev/null +++ b/Doc/SerializationSettings.aml @@ -0,0 +1,326 @@ + + + + + + JsonSerializer has a number of properties on it to customize how it serializes JSON. These can also be used with the methods on JsonConvert via the JsonSerializerSettings overloads. + + +
+ DateFormatHandling + DateFormatHandling controls how dates are serialized. + + + + + Member + Description + + + + IsoDateFormat + By default Json.NET writes dates in the ISO 8601 format, e.g. "2012-03-21T05:40Z". + + + MicrosoftDateFormat + Dates are written in the Microsoft JSON format, e.g. "\/Date(1198908717056)\/". + +
+ +
+
+ +
+ MissingMemberHandling + MissingMemberHandling controls how missing members, e.g. JSON contains a property that isn't a member on the object, are handled during deserialization. + + + + + Member + Description + + + + Ignore + By default Json.NET ignores JSON if there is no field or property for its value to be set to during deserialization. + + + Error + Json.NET errors when there is a missing member during deserialization. + +
+ +
+
+ +
+ ReferenceLoopHandling + ReferenceLoopHandling controls how circular referencing objects, e.g. a Person object referencing itself via a Manager property, are serialized. + + + + + Member + Description + + + + Error + By default Json.NET will error if a reference loop is encountered (otherwise the serializer will get into an infinite loop). + + + Ignore + Json.NET will ignore objects in reference loops and not serialize them. The first time an object is encountered it will be serialized as usual but if the object is encountered as a child object of itself the serializer will skip serializing it. + + + Serialize + This option forces Json.NET to serialize objects in reference loops. This is useful if objects are nested but not indefinitely. + +
+ReferenceLoopHandling can also be customized on individual properties with JsonPropertyAttribute. +
+
+ +
+ NullValueHandling + NullValueHandling controls how null values on .NET objects are handled during serialization and how null values in JSON are handled during deserialization. + + + + + Member + Description + + + + Include + By default Json.NET writes null values to JSON when serializing and sets null values to fields/properties when deserializing. + + + Ignore + Json.NET will skip writing JSON properties if the .NET value is null when serializing and will skip setting fields/properties if the JSON property is null when deserializing. + +
+NullValueHandling can also be customized on individual properties with JsonPropertyAttribute. + +
+
+ +
+ DefaultValueHandling + DefaultValueHandling controls how Json.NET uses default values set using the .NET DefaultValueAttribute when serializing and deserializing. + + + + + Member + Description + + + + Include + By default Json.NET will write a field/property value to JSON when serializing if the value is the same as the field/property's default value. The Json.NET deserializer will continue setting a field/property if the JSON value is the same as the default value. + + + Ignore + Json.NET will skip writing a field/property value to JSON if the value is the same as the field/property's default value. The Json.NET deserializer will skip setting a .NET object's field/property if the JSON value is the same as the default value. + +
+DefaultValueHandling can also be customized on individual properties with JsonPropertyAttribute. + +
+
+ +
+ ObjectCreationHandling + ObjectCreationHandling controls how objects are created and deserialized to during deserialization. + + + + + Member + Description + + + + Auto + By default Json.NET will attempt to set JSON values onto existing objects and add JSON values to existing collections during deserialization. + + + Reuse + Same behaviour as auto. + + + Replace + Json.NET will always recreate objects and collections before setting values to them during deserialization. + +
+ObjectCreationHandling can also be customized on individual properties with JsonPropertyAttribute. + +
+
+ +
+ TypeNameHandling + TypeNameHandling controls whether Json.NET includes .NET type names during serialization with a $type property and reads .NET type names from that property to determine what type to create during deserialization. + + + + + Member + Description + + + + None + By default Json.NET does not read or write type names during deserialization. + + + Objects + Json.NET will write and use type names for objects but not collections. + + + Arrays + Json.NET will write and use type names for collections but not objects. + + + Auto + Json.NET will check whether an object/collection matches its declared property and writes the type name if they do not match, e.g. a property with a type of Mammal has a derived instance of Dog assigned. Auto will ensure that type information isn't lost when serializing/deserializing automatically without having to write type names for every object. + + + All + Json.NET will write and use type names for objects and collections. + +
+TypeNameHandling can also be customized on individual properties with JsonPropertyAttribute. + +
+
+ +
+ TypeNameAssemblyFormat + TypeNameAssemblyFormat controls how type names are written during serialization. + + + + + Member + Description + + + + Simple + By default Json.NET writes the partial assembly name with the type, e.g. System.Data.DataSet, System.Data. Note that Silverlight and Windows Phone are not able to use this format. + + + Full + Json.NET will write the full assembly name, including version number, culture and public key token. + +
+Read more about the valid values at T:System.Runtime.Serialization.Formatters.FormatterAssemblyStyle. + +
+
+ +
+ Binder + The serialization binder is used to resolve type names to a .NET type. + Read more about the serialization binder here: T:System.Runtime.Serialization.SerializationBinder + +
+ +
+ ConstructorHandling + ConstructorHandling controls how constructors are used when initializing objects during deserialization. + + + + + Member + Description + + + + Default + By default Json.NET will first look for a constructor marked with the JsonConstructorAttribute, then look for a public default constructor + (a constructor that doesn't take any arguments), then check if the class has a single public constructor with arguments and finally check for a + non-public default constructor. If the class has multiple public constructors with arguments an error will be thrown. This can be fixed by + marking one of the constructors with the JsonConstructorAttribute. + + + AllowNonPublicDefaultConstructor + Json.NET will use a classes private default constructor before constructors with arguments if available. + +
+ +
+
+ +
+ Converters + This is the collection of JsonConverters that will be used during serialization and deserialization. + JsonConverters allows JSON to be manually written during serialization and read during deserialization. + This is useful for particularly complex JSON structures or for when you want to change how a type is serialized. + When a JsonConverter has been added to a JsonSerializer it will be checked for every value that is being serialized/deserialized + using its CanConvert to see if it should be used. If CanConvert returns true then the JsonConverter will be used to read or write + the JSON for that value. Note that while a JsonConverter gives you complete control over that values JSON, many Json.NET serialization + features are no longer available like type name and reference handling. + To create your own custom converter inherit from the JsonConverter class. Read more about the built-in JsonConverters below: + + + + +Serializing Dates in JSON +DatesInJSON.htm +_self + + +Converting between JSON and XML +ConvertingJSONandXML.htm +_self + + +CustomCreationConverter +CustomCreationConverter.htm +_self + + T:Newtonsoft.Json.Converters.StringEnumConverter + + + + +
+ +
+ ContractResolver + Internally for every .NET type the JsonSerializer will create a contract of how the type should be serialized and deserialized, + based on type metadata and attributes applied to the class. Specifying a custom IContractResolver allows the creation of contracts to be customized. + Read more about Contract Resolvers here: +Contract Resolvers +ContractResolver.htm +_self + + +
+ +
+ Error + The Error event can catch errors during serialization and either handle the event and continue with + serialization or let the error bubble up and be thrown to the application. + Read more about error handling here: +Serialization Error Handling +SerializationErrorHandling.htm +_self + + + +
+ + +
+
\ No newline at end of file diff --git a/Doc/SerializationSettings.html b/Doc/SerializationSettings.html deleted file mode 100644 index 98c3c1cd..00000000 --- a/Doc/SerializationSettings.html +++ /dev/null @@ -1,513 +0,0 @@ - - - - Serialization Settings - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Serialization Settings
- -
- - -

JsonSerializer has a number of properties on it to customize how it serializes - JSON. These can also be used with the methods on JsonConvert via the - JsonSerializerSettings overloads.

- -

DateFormatHandling

-

DateFormatHandling controls how dates are serialized.

- - - - - - - - - - - - - - - -
- Member - - Description -
- IsoDateFormat - -
- By default Json.NET writes dates in the ISO 8601 format, e.g. "2012-03-21T05:40Z". -
-
-
- MicrosoftDateFormat - -
- Dates are written in the Microsoft JSON format, e.g. "\/Date(1198908717056)\/". -
-
-
-

MissingMemberHandling

-

MissingMemberHandling controls how missing members, e.g. JSON contains a property - that isn't a member on the object, are handled during deserialization.

- - - - - - - - - - - - - - - -
- Member - - Description -
- Ignore - -
- By default Json.NET ignores JSON if there is no field - or property for its value to be set to during deserialization. -
-
-
- Error - -
- Json.NET errors when there is a missing member during - deserialization. -
-
-
- -

ReferenceLoopHandling

-

ReferenceLoopHandling controls how circular referencing objects, e.g. a Person - object referencing itself via a Manager property, are serialized.

- - - - - - - - - - - - - - - - - - - -
- Member - - Description -
- Error - -
- By default Json.NET will error if a reference loop is - encountered (otherwise the serializer will get into an infinite loop). -
-
-
- Ignore - -
- Json.NET will ignore objects in reference loops and - not serialize them. The first time an object is encountered it will be - serialized as usual but if the object is encountered as a child object of itself - the serializer will skip serializing it. -
-
-
- Serialize - -
- This option forces Json.NET to serialize objects in - reference loops. This is useful if objects are nested but not indefinitely. -
-
-
- -

ReferenceLoopHandling can also be customized on individual properties with JsonPropertyAttribute.

-

NullValueHandling

-

NullValueHandling controls how null values on .NET objects are handled during - serialization and how null values in JSON are handled during deserialization.

- - - - - - - - - - - - - - - -
- Member - - Description -
- Include - -
- By default Json.NET writes null values to JSON when - serializing and sets null values to fields/properties when deserializing. -
-
-
- Ignore - -
- Json.NET will skip writing JSON properties if the .NET - value is null when serializing and will skip setting fields/properties if the - JSON property is null when deserializing. -
-
-
- -

NullValueHandling can also be customized on individual properties with JsonPropertyAttribute.

-

- DefaultValueHandling

-

-DefaultValueHandling controls how Json.NET uses default values set using the .NET - DefaultValueAttribute when serializing and deserializing.

- - - - - - - - - - - - - - - -
- Member - - Description -
- Include - -
- By default Json.NET will write a field/property value - to JSON when serializing if the value is the same as the field/property's - default value. The Json.NET deserializer will continue setting a field/property - if the JSON value is the same as the default value. -
-
-
- Ignore - -
- Json.NET will skip writing a field/property value to - JSON if the value is the same as the field/property's default value. The - Json.NET deserializer will skip setting a .NET object's field/property if the - JSON value is the same as the default value. -
-
-
- -

DefaultValueHandling can also be customized on individual properties with JsonPropertyAttribute.

-

ObjectCreationHandling

-

ObjectCreationHandling controls how objects are created and deserialized to - during deserialization.

- - - - - - - - - - - - - - - - - - - -
- Member - - Description -
- Auto - -
- By default Json.NET will attempt to set JSON values onto - existing objects and add JSON values to existing collections during - deserialization. -
-
-
- Reuse - -
- Same behaviour as auto. -
-
-
- Replace - -
- Json.NET will always recreate objects and collections - before setting values to them during deserialization. -
-
-
- -

ObjectCreationHandling can also be customized on individual properties with JsonPropertyAttribute.

-

TypeNameHandling

-

TypeNameHandling controls whether Json.NET includes .NET type names during - serialization with a $type property and reads .NET type names from that property - to determine what type to create during deserialization.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Member - - Description -
- None - -
- By default Json.NET does not read or write type names - during deserialization. -
-
-
- Objects - -
- Json.NET will write and use type names for objects - but not collections. -
-
-
- Arrays - -
- Json.NET will write and use type names for collections - but not objects. -
-
-
- Auto - -
- Json.NET will check whether an object/collection matches - its declared property and writes the type name if they do not match, e.g. a - property with a type of Mammal has a derived instance of Dog assigned. Auto will - ensure that type information isn't lost when serializing/deserializing - automatically without having to write type names for every object. -
-
-
- All - -
- Json.NET will write and use type names for objects and - collections. -
-
-
- -

TypeNameHandling can also be customized on individual properties with JsonPropertyAttribute.

-

TypeNameAssemblyFormat

-

TypeNameAssemblyFormat controls how type names are written during serialization.

- - - - - - - - - - - - - - - -
- Member - - Description -
- Simple - -
- By default Json.NET writes the partial assembly name - with the type, e.g. System.Data.DataSet, System.Data. Note that Silverlight and - Windows Phone are not able to use this format. -
-
-
- Full - -
- Json.NET will write the full assembly name, including - version number, culture and public key token. -
-
-
- -

Read more about the valid values at - - FormatterAssemblyStyle.

-

Binder

-

The serialization binder is used to resolve type names to a .NET type.

-

Read more about the serialization binder here: - SerializationBinder

-

ConstructorHandling

-

ConstructorHandling controls how constructors are used when initializing objects - during deserialization.

- - - - - - - - - - - - - - - -
- Member - - Description -
- Default - -
- By default Json.NET will first look for a constructor - marked with the JsonConstructorAttribute, then look for a public default - constructor (a constructor that doesn't take any arguments), then check if - the class has a single public constructor with arguments and finally check - for a non-public default constructor. If the class has multiple public - constructors with arguments an error will be thrown. This can be fixed by - marking one of the constructors with the JsonConstructorAttribute. -
-
-
- AllowNonPublicDefaultConstructor - -
- Json.NET will use a classes private default constructor before constructors - with arguments if available. -
-
-
- -

Converters

-

This is the collection of JsonConverters that will be used during serialization - and deserialization.

-

JsonConverters allows JSON to be manually written during serialization and read - during deserialization. This is useful for particularly complex JSON structures - or for when you want to change how a type is serialized.

-

When a JsonConverter has been added to a JsonSerializer it will be checked for - every value that is being serialized/deserialized using its CanConvert to see if - it should be used. If CanConvert returns true then the JsonConverter will be - used to read or write the JSON for that value. Note that while a JsonConverter - gives you complete control over that values JSON, many Json.NET serialization - features are no longer available like type name and reference handling.

-

To create your own custom converter inherit from the JsonConverter class. Read - more about the built-in JsonConverters below:

- -

ContractResolver

-

Internally for every .NET type the JsonSerializer will create a contract of how - the type should be serialized and deserialized, based on type metadata and - attributes applied to the class. Specifying a custom IContractResolver allows - the creation of contracts to be customized.

-

Read more about Contract Resolvers here: Contract - Resolvers

-

Error

-

The Error event can catch errors during serialization and either handle the event - and continue with serialization or let the error bubble up and be thrown to the - application.

-

Read more about error handling here: - Serialization Error Handling

- - - -
- - - - \ No newline at end of file diff --git a/Doc/SerializingCollections.aml b/Doc/SerializingCollections.aml new file mode 100644 index 00000000..46101c26 --- /dev/null +++ b/Doc/SerializingCollections.aml @@ -0,0 +1,57 @@ + + + + + + + + Json.NET has excellent support for serializing and deserializing + collections of objects. + + +
+ Serializing Collections + + + To serialize a collection - a generic list, array, dictionary, or + your own custom collection - simply call the serializer with the object + you want to get JSON for. Json.NET will serialize the collection and all + of the values it contains. + + + +
+
+ Deserializing Collections + + + To deserialize JSON into a .NET collection just specify the collection + type you want to deserialize to. Json.NET supports a wide range of collection + types. + + +
+
+ Deserializing Dictionaries + + + Using Json.NET you can also deserialize a JSON object into a .NET + generic dictionary. The JSON object's property names and values will be + added to the dictionary. + + +
+
+
\ No newline at end of file diff --git a/Doc/SerializingCollections.html b/Doc/SerializingCollections.html deleted file mode 100644 index 53e59d32..00000000 --- a/Doc/SerializingCollections.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - Serializing Collections - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Serializing Collections
- -
- - -

The JsonSerializer has - great support for serializing and deserializing collections of objects.

- -

Serializing

-

To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for. - Json.NET will serialize the collection and all of the values it contains.

- - -
- -
-
Product p1 = new Product
-
  {
-
    Name = "Product 1",
-
    Price = 99.95m,
-
    ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
-
  };
-
Product p2 = new Product
-
{
-
  Name = "Product 2",
-
  Price = 12.50m,
-
  ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
-
};
-
 
-
List<Product> products = new List<Product>();
-
products.Add(p1);
-
products.Add(p2);
-
 
-
string json = JsonConvert.SerializeObject(products, Formatting.Indented);
-
//[
-
//  {
-
//    "Name": "Product 1",
-
//    "ExpiryDate": "\/Date(978048000000)\/",
-
//    "Price": 99.95,
-
//    "Sizes": null
-
//  },
-
//  {
-
//    "Name": "Product 2",
-
//    "ExpiryDate": "\/Date(1248998400000)\/",
-
//    "Price": 12.50,
-
//    "Sizes": null
-
//  }
-
//]
-
- -
- -

Deserializing

-

To deserialize JSON into a .NET collection just specify the collection type you want to deserialize to. Json.NET supports a wide range of collection types.

- -
- -
-
string json = @"[
-
  {
-
    ""Name"": ""Product 1"",
-
    ""ExpiryDate"": ""\/Date(978048000000)\/"",
-
    ""Price"": 99.95,
-
    ""Sizes"": null
-
  },
-
  {
-
    ""Name"": ""Product 2"",
-
    ""ExpiryDate"": ""\/Date(1248998400000)\/"",
-
    ""Price"": 12.50,
-
    ""Sizes"": null
-
  }
-
]";
-
 
-
List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
-
 
-
Console.WriteLine(products.Count);
-
// 2
-
 
-
Product p1 = products[0];
-
 
-
Console.WriteLine(p1.Name);
-
// Product 1
-
- -
- -

Deserializing Dictionaries

- -

Using Json.NET you can also deserialize a JSON object into a .NET generic dictionary. The JSON object's property names and values will be added to the dictionary.

- -
- -
-
string json = @"{""key1"":""value1"",""key2"":""value2""}";
-
 
-
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
-
 
-
Console.WriteLine(values.Count);
-
// 2
-
 
-
Console.WriteLine(values["key1"]);
-
// value1
-
- -
- - -
- - - - \ No newline at end of file diff --git a/Doc/SerializingJSON.aml b/Doc/SerializingJSON.aml new file mode 100644 index 00000000..df2d5a89 --- /dev/null +++ b/Doc/SerializingJSON.aml @@ -0,0 +1,56 @@ + + + + + + The quickest method of converting between JSON text and a .NET object is using the + T:Newtonsoft.Json.JsonSerializer. + The JsonSerializer converts .NET objects into their JSON equivalent and back again by mapping their properties to each other via name. + + +
+ JsonConvert + For simple scenarios where you want to convert to and from a JSON string the + M:Newtonsoft.Json.JsonConvert.SerializeObject(System.Object,Newtonsoft.Json.Formatting) and + M:Newtonsoft.Json.JsonConvert.DeserializeObject``1(System.String,Newtonsoft.Json.JsonSerializerSettings) + methods on JsonConvert provide an easy to use wrapper over JsonSerializer. + + + SerializeObject and DeserializeObject both have overloads that take a T:Newtonsoft.Json.JsonSerializerSettings object. + JsonSerializerSettings lets you use many of the JsonSerializer settings listed below while still using the simple serialization methods. + + +
+ + + + + +
+ JsonSerializer + For more control over how an object is serialized the T:Newtonsoft.Json.JsonSerializer can be used directly. +The JsonSerializer is able to read and write JSON text directly to a stream via T:Newtonsoft.Json.JsonTextReader +and T:Newtonsoft.Json.JsonTextWriter. +Other kinds of JsonWriters can also be used such as +T:Newtonsoft.Json.Linq.JTokenReader/T:Newtonsoft.Json.Linq.JTokenWriter +to convert your object to and from +LINQ to JSON objects or +T:Newtonsoft.Json.Bson.BsonReader/T:Newtonsoft.Json.Bson.BsonWriter to convert to and from BSON. + + + +JsonSerializer has a number of properties on it to customize how it serializes JSON. These can also be used with the methods on JsonConvert via the JsonSerializerSettings overloads. +Read more about the available JsonSerializer settings here: +Serialization Settings +SerializationSettings.htm +_self + + +
+
+
\ No newline at end of file diff --git a/Doc/SerializingJSON.html b/Doc/SerializingJSON.html deleted file mode 100644 index c4729c34..00000000 --- a/Doc/SerializingJSON.html +++ /dev/null @@ -1,103 +0,0 @@ - - - - Serializing and Deserializing JSON - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Serializing and Deserializing JSON
- -
- - -

The quickest method of converting between JSON text and a .NET object is using - the JsonSerializer. The JsonSerializer converts .NET objects into their JSON - equivalent and back again.

- - -

For simple scenarios where you want to convert to and from a JSON string the SerializeObject and DeserializeObject methods on JsonConvert provide an easy to use wrapper over - JsonSerializer.

- - -
- -
-
Product product = new Product();
-
 
-
product.Name = "Apple";
-
product.Expiry = new DateTime(2008, 12, 28);
-
product.Price = 3.99M;
-
product.Sizes = new string[] { "Small", "Medium", "Large" };
-
 
-
string output = JsonConvert.SerializeObject(product);
-
//{
-
//  "Name": "Apple",
-
//  "Expiry": "\/Date(1230375600000+1300)\/",
-
//  "Price": 3.99,
-
//  "Sizes": [
-
//    "Small",
-
//    "Medium",
-
//    "Large"
-
//  ]
-
//}
-
 
-
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);
-
- -
- -

- SerializeObject and DeserializeObject both have overloads that take a - JsonSerializerSettings object. JsonSerializerSettings lets you use many of the JsonSerializer settings listed below while still using the simple serialization methods. -

- -

JsonSerializer

- - -

For more control over how an object is serialized the JsonSerializer can be used - directly. The JsonSerializer is able to read and write JSON text directly to - a stream via JsonTextReader and JsonTextWriter. Other kinds of JsonWriters can - also be used such as JTokenReader/JTokenWriter to - convert your object to and - from LINQ to JSON objects or BsonReader/BsonWriter to convert to and from BSON.

- -
- -
-
Product product = new Product();
-
product.Expiry = new DateTime(2008, 12, 28);
-
 
-
JsonSerializer serializer = new JsonSerializer();
-
serializer.Converters.Add(new JavaScriptDateTimeConverter());
-
serializer.NullValueHandling = NullValueHandling.Ignore;
-
 
-
using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
-
using (JsonWriter writer = new JsonTextWriter(sw))
-
{
-
  serializer.Serialize(writer, product);
-
  // {"Expiry":new Date(1230375600000),"Price":0}
-
}
-
- -
-

JsonSerializer has a number of properties on it to customize how it serializes JSON. - These can also be used with the methods on JsonConvert via the - JsonSerializerSettings overloads.

-

Read more about the available JsonSerializer settings here: - Serialization Settings

- - -
- - - - \ No newline at end of file diff --git a/Doc/SerializingJSONFragments.aml b/Doc/SerializingJSONFragments.aml new file mode 100644 index 00000000..d307083b --- /dev/null +++ b/Doc/SerializingJSONFragments.aml @@ -0,0 +1,19 @@ + + + + + + Often when working with large JSON documents you're only interested in a small + fragment of information. This scenario can be annoying when you want to serialize + that Json.NET into .NET objects because you have to define .NET classes for the + entire JSON result. + With Json.NET it is easy to get around this problem. Using LINQ to JSON you + can extract the pieces of JSON you want to serialize before passing them to the + Json.NET serializer. + + + + + + + \ No newline at end of file diff --git a/Doc/SerializingJSONFragments.html b/Doc/SerializingJSONFragments.html deleted file mode 100644 index dca923fd..00000000 --- a/Doc/SerializingJSONFragments.html +++ /dev/null @@ -1,125 +0,0 @@ - - - - Serializing Partial JSON Fragments - - - - - - -
- Json.NET - Quick Starts & API Documentation
- Serializing Partial JSON Fragments
- -
- -

Often when working with large JSON documents you're only interested in a small fragment of information. - This scenario can be annoying when you want to serialize that Json.NET into .NET - objects because you have to define .NET classes for the entire JSON result.

-

With Json.NET it is easy to get around this problem. Using LINQ to JSON you can - extract the pieces of JSON you want to serialize before passing them to the Json.NET serializer.

- -
-
- -
-
public class SearchResult
-
{
-
  public string Title { get; set; }
-
  public string Content { get; set; }
-
  public string Url { get; set; }
-
}
-
- -
-
- -
-
- -
-
string googleSearchText = @"{
-
  ""responseData"": {
-
    ""results"": [
-
      {
-
        ""GsearchResultClass"": ""GwebSearch"",
-
        ""unescapedUrl"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
-
        ""url"": ""http://en.wikipedia.org/wiki/Paris_Hilton"",
-
        ""visibleUrl"": ""en.wikipedia.org"",
-
        ""cacheUrl"": ""http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org"",
-
        ""title"": ""<b>Paris Hilton</b> - Wikipedia, the free encyclopedia"",
-
        ""titleNoFormatting"": ""Paris Hilton - Wikipedia, the free encyclopedia"",
-
        ""content"": ""[1] In 2006, she released her debut album...""
-
      },
-
      {
-
        ""GsearchResultClass"": ""GwebSearch"",
-
        ""unescapedUrl"": ""http://www.imdb.com/name/nm0385296/"",
-
        ""url"": ""http://www.imdb.com/name/nm0385296/"",
-
        ""visibleUrl"": ""www.imdb.com"",
-
        ""cacheUrl"": ""http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com"",
-
        ""title"": ""<b>Paris Hilton</b>"",
-
        ""titleNoFormatting"": ""Paris Hilton"",
-
        ""content"": ""Self: Zoolander. Socialite <b>Paris Hilton</b>...""
-
      }
-
    ],
-
    ""cursor"": {
-
      ""pages"": [
-
        {
-
          ""start"": ""0"",
-
          ""label"": 1
-
        },
-
        {
-
          ""start"": ""4"",
-
          ""label"": 2
-
        },
-
        {
-
          ""start"": ""8"",
-
          ""label"": 3
-
        },
-
        {
-
          ""start"": ""12"",
-
          ""label"": 4
-
        }
-
      ],
-
      ""estimatedResultCount"": ""59600000"",
-
      ""currentPageIndex"": 0,
-
      ""moreResultsUrl"": ""http://www.google.com/search?oe=utf8&ie=utf8...""
-
    }
-
  },
-
  ""responseDetails"": null,
-
  ""responseStatus"": 200
-
}";
-
 
-
JObject googleSearch = JObject.Parse(googleSearchText);
-
 
-
// get JSON result objects into a list
-
IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();
-
 
-
// serialize JSON results into .NET objects
-
IList<SearchResult> searchResults = new List<SearchResult>();
-
foreach (JToken result in results)
-
{
-
  SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
-
  searchResults.Add(searchResult);
-
}
-
 
-
// Title = <b>Paris Hilton</b> - Wikipedia, the free encyclopedia
-
// Content = [1] In 2006, she released her debut album...
-
// Url = http://en.wikipedia.org/wiki/Paris_Hilton
-
 
-
// Title = <b>Paris Hilton</b>
-
// Content = Self: Zoolander. Socialite <b>Paris Hilton</b>...
-
// Url = http://www.imdb.com/name/nm0385296/
-
- - -
-
- - -
- - - - \ No newline at end of file diff --git a/Doc/custom.css b/Doc/custom.css deleted file mode 100644 index 3bcd4804..00000000 --- a/Doc/custom.css +++ /dev/null @@ -1,19 +0,0 @@ -div#content { - padding: 0 10px 10px 10px; -} - -.overflowpanel -{ - width: 98%; - border: solid 1px #ccc; - overflow: auto; - overflow-y: hidden; - background-color: #fcfcfc; - margin-bottom: 1em; -} - -.overflowpanel .code -{ - padding: 10px 4px 20px 10px; - display: block; -} \ No newline at end of file diff --git a/Doc/doc.content b/Doc/doc.content new file mode 100644 index 00000000..cadaab66 --- /dev/null +++ b/Doc/doc.content @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Doc/doc.shfbproj b/Doc/doc.shfbproj index bc99aed1..81d7d1c8 100644 --- a/Doc/doc.shfbproj +++ b/Doc/doc.shfbproj @@ -19,7 +19,7 @@ Documentation - Summary, Parameter, Returns, AutoDocumentCtors, Namespace, TypeParameter + Summary, Parameter, Returns, AutoDocumentCtors, Namespace, TypeParameter, AutoDocumentDispose InheritedMembers, InheritedFrameworkMembers, Protected, SealedProtected @@ -31,10 +31,10 @@ - HtmlHelp1, MSHelpViewer, Website - .NET 3.5 - Json.NET - Quick Starts &amp%3b API Documentation - Prototype + Website + .NET 4.0.30319 + Json.NET - Documentation + vs2005 MemberName ..\Src\Newtonsoft.Json\bin\Release @@ -52,6 +52,71 @@ The <b>Newtonsoft.Json.Linq</b> namespace provides classes that are used to implement BSON. + True + API Reference + + + + + + + + {@HelpFormatOutputPaths} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {@CachedFrameworkCommentList} + {@CommentFileList} + + + + False @@ -60,30 +125,36 @@ - + - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + logo + logo + diff --git a/Doc/donate.gif b/Doc/donate.gif index d017250a..2d1ec159 100644 Binary files a/Doc/donate.gif and b/Doc/donate.gif differ diff --git a/Doc/logo.jpg b/Doc/logo.jpg new file mode 100644 index 00000000..3f099b18 Binary files /dev/null and b/Doc/logo.jpg differ diff --git a/Doc/styles.css b/Doc/styles.css deleted file mode 100644 index 47278fbb..00000000 --- a/Doc/styles.css +++ /dev/null @@ -1,439 +0,0 @@ -/* page style */ - -body { - margin: 0; - background-color: #FFFFFF; - padding: 0; - font-size: 8.5pt; - font-family: verdana, arial, sans-serif; - color: #000000; -} - -html>body { - margin: 0; - background-color: #FFFFFF; - padding: 0; - font-size: 8.5pt; - font-family: verdana, arial, sans-serif; - color: #000000; - overflow: auto; -} - -table { - /* this is a trick to force tables to inherit the body font size */ - font-size: 100%; -} - -/* non-scrolling (control) region style */ - -div#control { - margin: 0; - background-color: #D4DFFF; - padding: 4px; - width: 100%; - border-bottom-color: #C8CDDE; - border-bottom-style: solid; - border-bottom-width: 1px; - z-index: 2; -} - -span.productTitle { - font-size: 80%; -} - -span.topicTitle { - font-size: 140%; - font-weight: bold; - color: #003399; -} - -span#chickenFeet { - float: left; -} - -span#languageFilter { - float: right; - height: 1px; - max-height: 1px; - vertical-align: bottom; - overflow: visible; -} - -/* scrolling (content) region style */ - -div#main -{ - clear: both; - margin: 0; - padding: 1em; - width: 100%; - z-index: 1; - overflow: auto; -} - -/* sections */ - -div#header { - font-size: 80%; - color: #666666; - margin-bottom: 0.5em; -} - -div.summary { - margin-top: 0em; - margin-bottom: 1em; -} - -div.section { - margin-bottom: 1em; -} - -div.sectionTitle { - display: inline; - font-size: 120%; - font-weight: bold; - color: #003399; -} - -div.sectionContent { - margin-top: 0.2em; -} - -span.subsectionTitle { - font-weight: bold; -} - -div#footer { - margin-top: 1em; - border-top: thin solid #003399; - padding-top: 0.5em; -} - -div#footer p { - margin-top: 0.2em; - margin-bottom: 0.2em; -} - -/* authored content (block) */ - -p { - margin-top: 1em; - margin-bottom: 1em; -} - -dl, ul, ol { - margin-top: 0.5em; - margin-bottom: 0.5em; -} - -pre { - margin: 0; - padding: 0; - font-family: "Andale Mono", "Courier New", Courier, monospace; -} - -table.authoredTable { - table-layout: fixed; - width: 100%; - margin-bottom: 1em; -} - -table.authoredTable th { - border-bottom-color: #C8CDDE; - border-bottom-style: solid; - border-bottom-width: 1px; - background: #EFEFF7; - padding: 0.2em; - text-align: left; - color: #000066; - font-weight: bold; -} - -table.authoredTable td { - border-bottom-style: solid; - border-bottom-color: #C8CDDE; - border-bottom-width: 1px; - background: #F7F7FF; - padding: 0.2em; - vertical-align: top; -} - -div.alert { - border: 1px solid #C8CDDE; - background: #F7F7FF; -} - -div.media { - text-align: center; - margin-bottom: 1em; -} - - -/* authored content (inline) */ - -span.keyword { - font-weight: bold; -} - -span.code { - font-family: "Andale Mono", "Courier New", Courier, monospace; - font-size: 110%; - color: #000066; -} - -/* auto-generated controls */ - -div.langTabs { - /*width: 100%;*/ -} - -div.langTab { - float: left; - width: 15%; - border-top: 1px solid #C8CDDE; - border-left: 1px solid #C8CDDE; - border-right: 1px solid #C8CDDE; - background: #F7F7FF; - padding: 0.2em; - text-align: left; - color: #000066; - font-weight: normal; -} - -div.activeLangTab { - float: left; - width: 15%; - border-top: 1px solid #C8CDDE; - border-left: 1px solid #C8CDDE; - border-right: 1px solid #C8CDDE; - background: #EFEFF7; - padding: 0.2em; - text-align: left; - color: #000066; - font-weight: bold; -} - -table.members { - /* table-layout: fixed; */ - width: 100%; -} - -table.members th.iconColumn { - width: 60px; -} - -table.members th.nameColumn { - width: 40%; -} - -table.members th.descriptionColumn { - width: 60%; -} - -table.members th { - border-bottom-color: #C8CDDE; - border-bottom-style: solid; - border-bottom-width: 1px; - background: #EFEFF7; - padding: 0.2em; - text-align: left; - color: #000066; - font-weight: bold; -} - -table.members td { - border-bottom-style: solid; - border-bottom-color: #C8CDDE; - border-bottom-width: 1px; - background: #F7F7FF; - padding: 0.2em; - vertical-align: top; - overflow: hidden; -} - -table.exceptions { - table-layout: fixed; - width: 100%; -} - - -table.exceptions th.exceptionNameColumn { - width: 40%; -} - -table.exceptions th.exceptionConditionColumn { - width: 60%; -} - -table.exceptions th { - border-bottom-color: #C8CDDE; - border-bottom-style: solid; - border-bottom-width: 1px; - background: #EFEFF7; - padding: 0.2em; - text-align: left; - color: #000066; - font-weight: bold; -} - -table.exceptions td { - border-bottom-style: solid; - border-bottom-color: #C8CDDE; - border-bottom-width: 1px; - background: #F7F7FF; - padding: 0.2em; - vertical-align: top; -} - -table.permissions { - table-layout: fixed; - width: 100%; -} - - -table.permissions th.permissionNameColumn { - width: 40%; -} - -table.permissions th.permissionConditionColumn { - width: 60%; -} - -table.permissions th { - border-bottom-color: #C8CDDE; - border-bottom-style: solid; - border-bottom-width: 1px; - background: #EFEFF7; - padding: 0.2em; - text-align: left; - color: #000066; - font-weight: bold; -} - -table.permissions td { - border-bottom-style: solid; - border-bottom-color: #C8CDDE; - border-bottom-width: 1px; - background: #F7F7FF; - padding: 0.2em; - vertical-align: top; -} - -span.obsolete { - color: red; -} - -span.cs { - display: inline; -} - -span.vb { - display: none; -} - -span.cpp { - display: none; -} - -span.nu -{ - display: none; -} - -/* syntax styling */ - -div.code span.identifier { - font-weight: bold; -} - -div.code span.keyword { - color: green; -} - -div.code span.parameter { - font-style: italic; - color: purple; -} - -div.code span.literal { - color: purple; -} - -div.code span.comment { - color: red; -} - -span.foreignPhrase { - font-style: italic; -} - -span.placeholder { - font-style: italic; -} - -span.parameter -{ - font-style: italic; -} - -span.typeparameter -{ - font-style: italic; -} - -a { - color: blue; - text-decoration: none; -} - -a:hover { - text-decoration: underline; -} - -MSHelp\:link { - color: blue; - hoverColor: #3366ff; -} - -span.nolink { - font-weight: bold; -} - -span.selflink { - font-weight: bold; -} - -table.filter { - table-layout: fixed; -} - -tr.tabs td.tab { - width: 10em; - background: #F7F7FF; - padding: 0.2em; - text-align: left; - color: #000066; - font-weight: normal; - overflow: hidden; - cursor: pointer; -} - -tr.tabs td.activeTab { - width: 10em; - background: #EFEFF7; - padding: 0.2em; - text-align: left; - color: #000066; - font-weight: bold; - overflow: hidden; -} - -td.line { - background: #EFEFF7; -} - -dt { - font-weight: bold; - margin-top: 10px; - margin-left: 10px; -} diff --git a/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs index c6bff24b..867d413b 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs @@ -303,5 +303,16 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(1.1m, orderedValues[1]); Assert.AreEqual(1.2d, orderedValues[2]); } + + [Test] + public void WriteSingle() + { + float f = 5.2f; + JValue value = new JValue(f); + + string json = value.ToString(Formatting.None); + + Assert.AreEqual("5.2", json); + } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index 8337ddda..90f04df7 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -116,6 +116,10 @@ + + + + True True diff --git a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs index 31cbcb0f..ce3d7662 100644 --- a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs @@ -72,5 +72,5 @@ using System.Security; // by using the '*' as shown below: [assembly: AssemblyVersion("4.5.0.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.5.7.15115")] +[assembly: AssemblyFileVersion("4.5.7.15121")] #endif diff --git a/Src/Newtonsoft.Json/Bson/BsonWriter.cs b/Src/Newtonsoft.Json/Bson/BsonWriter.cs index d9ea1406..02b2e7fd 100644 --- a/Src/Newtonsoft.Json/Bson/BsonWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonWriter.cs @@ -464,7 +464,7 @@ namespace Newtonsoft.Json.Bson /// /// Writes a value that represents a BSON object id. /// - /// + /// The Object ID value to write. public void WriteObjectId(byte[] value) { ValidationUtils.ArgumentNotNull(value, "value"); diff --git a/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs b/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs index 2343ef95..15347590 100644 --- a/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs +++ b/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs @@ -31,7 +31,7 @@ namespace Newtonsoft.Json.Converters /// /// Create a custom object /// - /// + /// The object type to convert. public abstract class CustomCreationConverter : JsonConverter { /// @@ -70,7 +70,7 @@ namespace Newtonsoft.Json.Converters /// Creates an object which will then be populated by the serializer. /// /// Type of the object. - /// + /// The created object. public abstract T Create(Type objectType); /// diff --git a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs index 7f0100db..59ac00b2 100644 --- a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs +++ b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs @@ -37,9 +37,6 @@ using System.Linq; namespace Newtonsoft.Json.Converters { - /// - /// Converts an to and from its name string value. - /// /// /// Converts an to and from its name string value. /// diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 95063ac1..3ef15546 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -1167,6 +1167,7 @@ namespace Newtonsoft.Json.Linq /// /// Creates the specified .NET type from the . /// + /// The object type that the token will be deserialized to. /// The new object created from the JSON value. public T ToObject() { @@ -1176,6 +1177,7 @@ namespace Newtonsoft.Json.Linq /// /// Creates the specified .NET type from the using the specified . /// + /// The object type that the token will be deserialized to. /// The that will be used when creating the object. /// The new object created from the JSON value. public T ToObject(JsonSerializer jsonSerializer) diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs index 9ed6d14a..a164cd42 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -85,6 +85,15 @@ namespace Newtonsoft.Json.Linq { } + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(float value) + : this(value, JTokenType.Float) + { + } + /// /// Initializes a new instance of the class with the given value. /// @@ -531,7 +540,10 @@ namespace Newtonsoft.Json.Linq writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Float: - writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture)); + if (_value is float) + writer.WriteValue(_value); + else + writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture)); return; case JTokenType.String: writer.WriteValue((_value != null) ? _value.ToString() : null); diff --git a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs index 806bd1af..2c8177c2 100644 --- a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs @@ -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.7.15115")] +[assembly: AssemblyFileVersion("4.5.7.15121")] #endif [assembly: CLSCompliant(true)] diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 5f9a04a7..407f819e 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -486,7 +486,7 @@ namespace Newtonsoft.Json.Serialization /// Resolves the default for the contract. /// /// Type of the object. - /// + /// The contract's default . protected virtual JsonConverter ResolveContractConverter(Type objectType) { return JsonTypeReflector.GetJsonConverter(objectType.GetCustomAttributeProvider(), objectType); diff --git a/Src/Newtonsoft.Json/Serialization/ObjectConstructor.cs b/Src/Newtonsoft.Json/Serialization/ObjectConstructor.cs index 75f53879..b731707a 100644 --- a/Src/Newtonsoft.Json/Serialization/ObjectConstructor.cs +++ b/Src/Newtonsoft.Json/Serialization/ObjectConstructor.cs @@ -28,5 +28,6 @@ namespace Newtonsoft.Json.Serialization /// /// Represents a method that constructs an object. /// + /// The object type to create. public delegate object ObjectConstructor(params object[] args); } \ No newline at end of file