-Added support to deserializing to IEnumerable<T>, IList<T>, IDictionary<K, V>

-Added populating members when creating object from non default constructor
-Added case best match when deserializing properties
-Added ToString(Formatting, JsonConverters[]) overload to JToken
-Added SerializeObject(object, Formatting, JsonConverter[]) overload to JsonConvert
-Added IMappingResolver. Property added to JsonSerializer, JsonSerializerSettings, JsonSchemaGenerator
-Added CamelCaseMappingResolver
This commit is contained in:
JamesNK
2009-03-14 00:38:28 +00:00
parent e5eaa14990
commit 9fd47e6334
24 changed files with 873 additions and 206 deletions
+109 -7
View File
@@ -777,14 +777,28 @@ keyword such as type of business.""
name.pNumbers.Add(p1);
name.pNumbers.Add(p2);
string json = JsonConvert.SerializeObject(name);
string json = JsonConvert.SerializeObject(name, Formatting.Indented);
Assert.AreEqual(@"{
""personsName"": ""The Idiot in Next To Me"",
""pNumbers"": [
{
""phoneNumber"": ""555-1212""
},
{
""phoneNumber"": ""444-1212""
}
]
}", json);
Name newName = JsonConvert.DeserializeObject<Name>(json);
Assert.AreEqual("The Idiot in Next To Me", newName.personsName);
// not passed in as part of the constructor, values not deserialized
Assert.AreEqual(0, newName.pNumbers.Count);
// not passed in as part of the constructor but assigned to pNumbers property
Assert.AreEqual(2, newName.pNumbers.Count);
Assert.AreEqual("555-1212", newName.pNumbers[0].phoneNumber);
Assert.AreEqual("444-1212", newName.pNumbers[1].phoneNumber);
}
[Test]
@@ -1323,15 +1337,103 @@ keyword such as type of business.""
Console.WriteLine(javascriptJson);
}
public class SomeClass
public void GenericListAndDictionaryInterfaceProperties()
{
public int? SomeProp { get; set; }
GenericListAndDictionaryInterfaceProperties o = new GenericListAndDictionaryInterfaceProperties();
o.IDictionaryProperty = new Dictionary<string, int>
{
{"one", 1},
{"two", 2},
{"three", 3}
};
o.IListProperty = new List<int>
{
1, 2, 3
};
o.IEnumerableProperty = new List<int>
{
4, 5, 6
};
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
Assert.AreEqual(@"{
""IEnumerableProperty"": [
4,
5,
6
],
""IListProperty"": [
1,
2,
3
],
""IDictionaryProperty"": {
""one"": 1,
""two"": 2,
""three"": 3
}
}", json);
GenericListAndDictionaryInterfaceProperties deserializedObject = JsonConvert.DeserializeObject<GenericListAndDictionaryInterfaceProperties>(json);
Assert.IsNotNull(deserializedObject);
CollectionAssert.AreEqual(o.IListProperty.ToArray(), deserializedObject.IListProperty.ToArray());
CollectionAssert.AreEqual(o.IEnumerableProperty.ToArray(), deserializedObject.IEnumerableProperty.ToArray());
CollectionAssert.AreEqual(o.IDictionaryProperty.ToArray(), deserializedObject.IDictionaryProperty.ToArray());
}
public class PropertyCase
{
public string firstName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string lastName { get; set; }
}
[Test]
public void Main()
public void DeserializeBestMatchPropertyCase()
{
var pokes = JsonConvert.DeserializeObject<SomeClass>(@"{""SomeProp"":1}");
string json = @"{
""firstName"": ""firstName"",
""FirstName"": ""FirstName"",
""LastName"": ""LastName"",
""lastName"": ""lastName"",
}";
PropertyCase o = JsonConvert.DeserializeObject<PropertyCase>(json);
Assert.IsNotNull(o);
Assert.AreEqual("firstName", o.firstName);
Assert.AreEqual("FirstName", o.FirstName);
Assert.AreEqual("LastName", o.LastName);
Assert.AreEqual("lastName", o.lastName);
}
public class SuperKlass
{
public string SuperProp { get; set; }
public SuperKlass() { SuperProp = "default superprop"; }
}
public class SubKlass : SuperKlass
{
public string SubProp { get; set; }
public SubKlass(string subprop) { SubProp = subprop; }
}
public void DeserializePropertiesOnToNonDefaultConstructor()
{
SubKlass i = new SubKlass("my subprop");
i.SuperProp = "overrided superprop";
string json = JsonConvert.SerializeObject(i);
Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", json);
SubKlass ii = JsonConvert.DeserializeObject<SubKlass>(json);
string newJson = JsonConvert.SerializeObject(ii);
Assert.AreEqual(@"{""SubProp"":""my subprop"",""SuperProp"":""overrided superprop""}", newJson);
}
}
}
+14 -1
View File
@@ -506,7 +506,7 @@ namespace Newtonsoft.Json.Tests.Linq
new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc))
);
string json = a.ToString(new IsoDateTimeConverter());
string json = a.ToString(Formatting.Indented, new IsoDateTimeConverter());
Assert.AreEqual(@"[
""2009-02-15T00:00:00.0000000Z""
@@ -517,6 +517,19 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(@"[""2009-02-15T00:00:00.0000000Z""]", json);
}
[Test]
public void ToStringWithNoIndenting()
{
JArray a =
new JArray(
new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc))
);
string json = a.ToString(Formatting.None, new IsoDateTimeConverter());
Assert.AreEqual(@"[""2009-02-15T00:00:00.0000000Z""]", json);
}
[Test]
public void AddAfterSelf()
{
@@ -58,6 +58,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Serialization\CamelCaseMappingResolverTests.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
@@ -75,6 +76,7 @@
<Compile Include="TestObjects\DefaultValueAttributeTestClass.cs" />
<Compile Include="TestObjects\DoubleClass.cs" />
<Compile Include="TestObjects\GenericImpl.cs" />
<Compile Include="TestObjects\GenericListAndDictionaryInterfaceProperties.cs" />
<Compile Include="TestObjects\GetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\IncompatibleJsonAttributeClass.cs" />
<Compile Include="TestObjects\Invoice.cs" />
@@ -86,6 +88,7 @@
<Compile Include="TestObjects\Name.cs" />
<Compile Include="TestObjects\PersonRaw.cs" />
<Compile Include="TestObjects\PhoneNumber.cs" />
<Compile Include="TestObjects\PrivateMembersClass.cs" />
<Compile Include="TestObjects\RequiredMembersClass.cs" />
<Compile Include="TestObjects\SetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\Article.cs" />
@@ -63,6 +63,7 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Serialization\CamelCaseMappingResolverTests.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
@@ -80,6 +81,7 @@
<Compile Include="TestObjects\DefaultValueAttributeTestClass.cs" />
<Compile Include="TestObjects\DoubleClass.cs" />
<Compile Include="TestObjects\GenericImpl.cs" />
<Compile Include="TestObjects\GenericListAndDictionaryInterfaceProperties.cs" />
<Compile Include="TestObjects\GetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\IncompatibleJsonAttributeClass.cs" />
<Compile Include="TestObjects\Invoice.cs" />
@@ -91,6 +93,7 @@
<Compile Include="TestObjects\Name.cs" />
<Compile Include="TestObjects\PersonRaw.cs" />
<Compile Include="TestObjects\PhoneNumber.cs" />
<Compile Include="TestObjects\PrivateMembersClass.cs" />
<Compile Include="TestObjects\RequiredMembersClass.cs" />
<Compile Include="TestObjects\SetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\Article.cs" />
@@ -81,6 +81,7 @@
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Serialization\CamelCaseMappingResolverTests.cs" />
<Compile Include="TestObjects\AbstractGenericBase.cs" />
<Compile Include="TestObjects\ArgumentConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\BadJsonPropertyClass.cs" />
@@ -94,6 +95,7 @@
<Compile Include="TestObjects\DefaultValueAttributeTestClass.cs" />
<Compile Include="TestObjects\DoubleClass.cs" />
<Compile Include="TestObjects\GenericImpl.cs" />
<Compile Include="TestObjects\GenericListAndDictionaryInterfaceProperties.cs" />
<Compile Include="TestObjects\GetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\IncompatibleJsonAttributeClass.cs" />
<Compile Include="TestObjects\Invoice.cs" />
@@ -105,6 +107,7 @@
<Compile Include="TestObjects\Name.cs" />
<Compile Include="TestObjects\PersonRaw.cs" />
<Compile Include="TestObjects\PhoneNumber.cs" />
<Compile Include="TestObjects\PrivateMembersClass.cs" />
<Compile Include="TestObjects\RequiredMembersClass.cs" />
<Compile Include="TestObjects\SetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\Article.cs" />
@@ -281,14 +281,27 @@ namespace Newtonsoft.Json.Tests.Schema
Assert.AreEqual(JsonSchemaType.String, schema.Type);
}
public class CustomDirectoryInfoSerializer : JsonSerializer
//public class CustomDirectoryInfoSerializer : JsonSerializer
//{
// protected override Newtonsoft.Json.Serialization.JsonMemberMappingCollection GetMemberMappings(Type objectType)
// {
// JsonMemberMappingCollection mappings = base.GetMemberMappings(objectType);
// JsonMemberMappingCollection c = new JsonMemberMappingCollection();
// CollectionUtils.AddRange(c, (IEnumerable) mappings.Where(m => m.MappingName != "Root"));
// return c;
// }
//}
public class CustomDirectoryInfoMapper : DefaultMappingResolver
{
protected override Newtonsoft.Json.Serialization.JsonMemberMappingCollection GetMemberMappings(Type objectType)
public override JsonMemberMappingCollection ResolveMappings(Type type)
{
JsonMemberMappingCollection mappings = base.GetMemberMappings(objectType);
JsonMemberMappingCollection mappings = base.ResolveMappings(type);
JsonMemberMappingCollection c = new JsonMemberMappingCollection();
CollectionUtils.AddRange(c, (IEnumerable) mappings.Where(m => m.MappingName != "Root"));
CollectionUtils.AddRange(c, (IEnumerable)mappings.Where(m => m.MappingName != "Root"));
return c;
}
@@ -366,9 +379,10 @@ namespace Newtonsoft.Json.Tests.Schema
DirectoryInfo temp = new DirectoryInfo(@"c:\temp");
JsonTokenWriter jsonWriter = new JsonTokenWriter();
CustomDirectoryInfoSerializer customSerializer = new CustomDirectoryInfoSerializer();
customSerializer.Converters.Add(new IsoDateTimeConverter());
customSerializer.Serialize(jsonWriter, temp);
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new IsoDateTimeConverter());
serializer.MappingResolver = new CustomDirectoryInfoMapper();
serializer.Serialize(jsonWriter, temp);
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
@@ -377,5 +391,76 @@ namespace Newtonsoft.Json.Tests.Schema
Assert.AreEqual("Non-optional properties are missing from object: Root.", errors[0]);
Assert.AreEqual("Non-optional properties are missing from object: Root.", errors[1]);
}
[Test]
public void GenerateSchemaCamelCase()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.MappingResolver = new CamelCaseMappingResolver();
JsonSchema schema = generator.Generate(typeof (DirectoryInfo), true);
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""System.IO.DirectoryInfo"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""name"": {
""type"": [
""string"",
""null""
]
},
""parent"": {
""$ref"": ""System.IO.DirectoryInfo""
},
""exists"": {
""type"": ""boolean""
},
""root"": {
""$ref"": ""System.IO.DirectoryInfo""
},
""fullName"": {
""type"": [
""string"",
""null""
]
},
""extension"": {
""type"": [
""string"",
""null""
]
},
""creationTime"": {
""type"": ""string""
},
""creationTimeUtc"": {
""type"": ""string""
},
""lastAccessTime"": {
""type"": ""string""
},
""lastAccessTimeUtc"": {
""type"": ""string""
},
""lastWriteTime"": {
""type"": ""string""
},
""lastWriteTimeUtc"": {
""type"": ""string""
},
""attributes"": {
""type"": ""integer""
}
}
}", json);
}
}
}
@@ -0,0 +1,122 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Serialization;
using NUnit.Framework;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
public class CamelCaseMappingResolverTests : TestFixtureBase
{
[Test]
public void JsonConvertSerializerSettings()
{
Person person = new Person();
person.BirthDate = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.LastModified = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.Name = "Name!";
string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
MappingResolver = new CamelCaseMappingResolver()
});
Assert.AreEqual(@"{
""name"": ""Name!"",
""birthDate"": ""\/Date(974764544000)\/"",
""lastModified"": ""\/Date(974764544000)\/""
}", json);
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json, new JsonSerializerSettings
{
MappingResolver = new CamelCaseMappingResolver()
});
Assert.AreEqual(person.BirthDate, deserializedPerson.BirthDate);
Assert.AreEqual(person.LastModified, deserializedPerson.LastModified);
Assert.AreEqual(person.Name, deserializedPerson.Name);
}
[Test]
public void JsonTokenWriter()
{
JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();
ignoreAttributeOnClassTestClass.Field = int.MinValue;
JsonSerializer serializer = new JsonSerializer();
serializer.MappingResolver = new CamelCaseMappingResolver();
JsonTokenWriter writer = new JsonTokenWriter();
serializer.Serialize(writer, ignoreAttributeOnClassTestClass);
JObject o = (JObject) writer.Token;
JProperty p = o.Property("theField");
Assert.IsNotNull(p);
Assert.AreEqual(int.MinValue, (int)p.Value);
string json = o.ToString();
}
[Test]
public void MemberSearchFlags()
{
PrivateMembersClass privateMembersClass = new PrivateMembersClass("PrivateString!", "InternalString!");
string json = JsonConvert.SerializeObject(privateMembersClass, Formatting.Indented, new JsonSerializerSettings
{
MappingResolver = new CamelCaseMappingResolver { MemberSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual(@"{
""_privateString"": ""PrivateString!"",
""i"": 0,
""_internalString"": ""InternalString!""
}", json);
PrivateMembersClass deserializedPrivateMembersClass = JsonConvert.DeserializeObject<PrivateMembersClass>(@"{
""_privateString"": ""Private!"",
""i"": -2,
""_internalString"": ""Internal!""
}", new JsonSerializerSettings
{
MappingResolver = new CamelCaseMappingResolver { MemberSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual("Private!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_privateString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
Assert.AreEqual("Internal!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_internalString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
Assert.AreEqual(-2, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
}
}
}
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class GenericListAndDictionaryInterfaceProperties
{
public IEnumerable<int> IEnumerableProperty { get; set; }
public IList<int> IListProperty { get; set; }
public IDictionary<string, int> IDictionaryProperty { get; set; }
}
}
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class PrivateMembersClass
{
public PrivateMembersClass(string privateString, string internalString)
{
_privateString = privateString;
_internalString = internalString;
}
public PrivateMembersClass()
{
}
private string _privateString;
private int i;
internal string _internalString;
}
}