From 6b19c9cf7246f5cea69953ce779795ac1d268b6f Mon Sep 17 00:00:00 2001 From: JamesNK Date: Fri, 19 Jun 2009 12:37:49 +0000 Subject: [PATCH] -More documentation -Changed CustomCreationConverter to throw NotImplementedException when serializing --- Src/Doc/CustomCreationConverter.html | 99 +++++++++++++++++++ Src/Doc/Introduction.html | 11 +-- Src/Doc/LINQtoJSON.html | 67 ++++++++++++- Src/Doc/ReadingWritingJSON.html | 2 +- Src/Doc/doc.shfb | 1 + Src/Doc/doc.sitemap | 1 + .../CustomCreationConverterTests.cs | 91 +++++++++++++++++ .../Linq/JObjectTests.cs | 6 ++ .../Newtonsoft.Json.Tests.csproj | 1 + .../TestObjects/Shortie.cs | 24 +---- Src/Newtonsoft.Json.sln | 1 + .../Converters/CustomCreationConverter.cs | 2 +- 12 files changed, 275 insertions(+), 31 deletions(-) create mode 100644 Src/Doc/CustomCreationConverter.html create mode 100644 Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs diff --git a/Src/Doc/CustomCreationConverter.html b/Src/Doc/CustomCreationConverter.html new file mode 100644 index 00000000..cd5c1f0f --- /dev/null +++ b/Src/Doc/CustomCreationConverter.html @@ -0,0 +1,99 @@ + + + + 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/Src/Doc/Introduction.html b/Src/Doc/Introduction.html index b30b5d03..e7c478c8 100644 --- a/Src/Doc/Introduction.html +++ b/Src/Doc/Introduction.html @@ -11,19 +11,18 @@

- The Json.NET library makes working with JavaScript and JSON formatted data in .NET - simple. Quickly read and write JSON using the JsonReader and JsonWriter or serialize + 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

History

@@ -49,9 +48,9 @@

Donate

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

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

- You can show your appreciation for Json.NET and support future development by donating.

+ You can show your support for Json.NET by donating. I really appreciate your feedback and support.

Donate

diff --git a/Src/Doc/LINQtoJSON.html b/Src/Doc/LINQtoJSON.html index 156b55d4..3eb12253 100644 --- a/Src/Doc/LINQtoJSON.html +++ b/Src/Doc/LINQtoJSON.html @@ -149,15 +149,20 @@

Querying JSON

-

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

-

Children returns all the children of that object. Values is similar to Children but it allows you to specify a type you would like the values to be converted into. Finally the property index is used to get a specific child, either by index position for JSON arrays or property name for JSON objects.

+

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 p.Value<string>("title");
+
  select (string)p["title"];
 
foreach (var item in postTitles)
{
@@ -183,6 +188,62 @@
//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
+
+
diff --git a/Src/Doc/ReadingWritingJSON.html b/Src/Doc/ReadingWritingJSON.html index ad37cc32..6d79db9b 100644 --- a/Src/Doc/ReadingWritingJSON.html +++ b/Src/Doc/ReadingWritingJSON.html @@ -73,8 +73,8 @@
JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));
 
-
// John Smith
Console.WriteLine(p.Name);
+
// John Smith
diff --git a/Src/Doc/doc.shfb b/Src/Doc/doc.shfb index 5508d344..7707d262 100644 --- a/Src/Doc/doc.shfb +++ b/Src/Doc/doc.shfb @@ -18,6 +18,7 @@ + Summary, Parameter, Returns, AutoDocumentCtors, Namespace, TypeParameter diff --git a/Src/Doc/doc.sitemap b/Src/Doc/doc.sitemap index 2002607b..29d306a7 100644 --- a/Src/Doc/doc.sitemap +++ b/Src/Doc/doc.sitemap @@ -4,6 +4,7 @@ + diff --git a/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs new file mode 100644 index 00000000..3ed49756 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Converters; + +namespace Newtonsoft.Json.Tests.Converters +{ + public class CustomCreationConverterTests : TestFixtureBase + { + 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 + { + public override IPerson Create(Type objectType) + { + return new Employee(); + } + } + + public void DeserializeObject() + { + string json = JsonConvert.SerializeObject(new List + { + new Employee + { + BirthDate = new DateTime(1977, 12, 30, 1, 1, 1, DateTimeKind.Utc), + FirstName = "Maurice", + LastName = "Moss", + Department = "IT", + JobTitle = "Support" + }, + new Employee + { + BirthDate = new DateTime(1978, 3, 15, 1, 1, 1, DateTimeKind.Utc), + FirstName = "Jen", + LastName = "Barber", + Department = "IT", + JobTitle = "Manager" + } + }, Formatting.Indented); + + //[ + // { + // "FirstName": "Maurice", + // "LastName": "Moss", + // "BirthDate": "\/Date(252291661000)\/", + // "Department": "IT", + // "JobTitle": "Support" + // }, + // { + // "FirstName": "Jen", + // "LastName": "Barber", + // "BirthDate": "\/Date(258771661000)\/", + // "Department": "IT", + // "JobTitle": "Manager" + // } + //] + + List people = JsonConvert.DeserializeObject>(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/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs index bb069655..8b49e92d 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs @@ -480,6 +480,12 @@ Parameter name: arrayIndex")] } }; + Console.WriteLine(shortie.Original); + // http://www.foo.com/ + + Console.WriteLine(shortie.Error.ErrorMessage); + // No action taken + Assert.AreEqual("http://www.foo.com/", shortie.Original); Assert.AreEqual("krehqk", shortie.Short); Assert.AreEqual(null, shortie.Shortened); diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index 68a8f8ae..ef62ef21 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -84,6 +84,7 @@ + diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/Shortie.cs b/Src/Newtonsoft.Json.Tests/TestObjects/Shortie.cs index 13aff870..f1691ec2 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/Shortie.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/Shortie.cs @@ -6,33 +6,17 @@ using System.Xml.Serialization; namespace Newtonsoft.Json.Tests.TestObjects { - [XmlRoot("short")] - [JsonObject(MemberSerialization.OptIn)] public class Shortie { - [JsonProperty("original")] - [XmlElement("original")] - public String Original { get; set; } - - [JsonProperty("shortened")] - [XmlElement("shortened")] - public String Shortened { get; set; } - - [JsonProperty("short")] - [XmlElement("short")] - public String Short { get; set; } - + public string Original { get; set; } + public string Shortened { get; set; } + public string Short { get; set; } public ShortieException Error { get; set; } } public class ShortieException { - [JsonProperty("code")] - [XmlElement("code")] public int Code { get; set; } - - [JsonProperty("msg")] - [XmlElement("msg")] - public String ErrorMessage { get; set; } + public string ErrorMessage { get; set; } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.sln b/Src/Newtonsoft.Json.sln index 984cdb5d..7cf957c2 100644 --- a/Src/Newtonsoft.Json.sln +++ b/Src/Newtonsoft.Json.sln @@ -15,6 +15,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Doc", "Doc", "{8F9E13D9-418 ProjectSection(SolutionItems) = preProject Doc\AdvanceSerializingJSON.html = Doc\AdvanceSerializingJSON.html Doc\custom.css = Doc\custom.css + Doc\CustomCreationConverter.html = Doc\CustomCreationConverter.html Doc\DatesInJSON.html = Doc\DatesInJSON.html Doc\doc.shfb = Doc\doc.shfb Doc\doc.sitemap = Doc\doc.sitemap diff --git a/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs b/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs index 5d952038..873a2536 100644 --- a/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs +++ b/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs @@ -44,7 +44,7 @@ namespace Newtonsoft.Json.Converters /// The calling serializer. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - serializer.Serialize(writer, value); + throw new NotSupportedException("CustomCreationConverter should only be used while deserializing."); } ///