-Modified project to support signed flag. Does not output InternalsVisibleTo attributes when present

-Improved error message on JObject and JArray Load method
-Added WriteRawValue
-Added missing XML documentation
-Added SerializeObject overload that takes a formatting flag
This commit is contained in:
JamesNK
2008-10-08 09:01:55 +00:00
parent 5bb0c17eec
commit 3038a8d79e
15 changed files with 144 additions and 207 deletions
@@ -1308,19 +1308,19 @@ keyword such as type of business.""
public void DefaultValueAttributeTest()
{
string json = JavaScriptConvert.SerializeObject(new DefaultValueAttributeTestClass(),
new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{""TestField1"":0,""TestProperty1"":null}", json);
json = JavaScriptConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = int.MinValue, TestProperty1 = "NotDefault" },
new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{""TestField1"":-2147483648,""TestProperty1"":""NotDefault""}", json);
json = JavaScriptConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = 21, TestProperty1 = "NotDefault" },
new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{""TestProperty1"":""NotDefault""}", json);
json = JavaScriptConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = 21, TestProperty1 = "TestProperty1Value" },
new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{}", json);
}
@@ -383,5 +383,32 @@ namespace Newtonsoft.Json.Tests
Assert.AreEqual("1", sw.ToString());
}
[Test]
public void WriteRawValue()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
int i = 0;
string rawJson = "[1,2]";
jsonWriter.WriteStartObject();
while (i < 3)
{
jsonWriter.WritePropertyName("d" + i);
jsonWriter.WriteRawValue(rawJson);
i++;
}
jsonWriter.WriteEndObject();
}
Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString());
}
}
}
@@ -290,5 +290,13 @@ Parameter name: index")]
Assert.AreEqual(j, v4.Parent);
Assert.AreEqual(1, j.IndexOf(v4));
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject")]
public void Parse_ShouldThrowOnUnexpectedToken()
{
string json = @"{""prop"":""value""}";
JArray.Parse(json);
}
}
}
@@ -309,5 +309,13 @@ Parameter name: arrayIndex")]
Assert.AreEqual("LastNameValue", raw.LastName);
Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Content);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray")]
public void Parse_ShouldThrowOnUnexpectedToken()
{
string json = @"[""prop""]";
JObject.Parse(json);
}
}
}
@@ -23,6 +23,9 @@
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<SignAssembly>false</SignAssembly>
<AssemblyOriginatorKeyFile>
</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
+7 -21
View File
@@ -1,11 +1,17 @@
#if PocketPC
#pragma warning disable 1591
// This class is... borrowed from .NET and Microsoft for a short time.
// Hopefully Microsoft will add DateTimeOffset to the compact framework
// or I will rewrite a striped down version of this file myself
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System;
namespace Newtonsoft.Json
namespace System
{
public struct DateTimeOffset : IComparable, IFormattable, IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>
{
@@ -312,26 +318,6 @@ namespace Newtonsoft.Json
return new DateTimeOffset(time.Ticks, offset);
}
//public override string ToString()
//{
// return DateTimeFormat.Format(this.ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, this.Offset);
//}
//public string ToString(IFormatProvider formatProvider)
//{
// return DateTimeFormat.Format(this.ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), this.Offset);
//}
//public string ToString(string format)
//{
// return DateTimeFormat.Format(this.ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, this.Offset);
//}
//public string ToString(string format, IFormatProvider formatProvider)
//{
// return DateTimeFormat.Format(this.ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), this.Offset);
//}
public string ToString(string format, IFormatProvider formatProvider)
{
if (!string.IsNullOrEmpty(format))
+25 -10
View File
@@ -436,7 +436,20 @@ namespace Newtonsoft.Json
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value)
{
return SerializeObject(value, (JsonSerializerSettings)null);
return SerializeObject(value, Formatting.None, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
}
/// <summary>
@@ -451,26 +464,28 @@ namespace Newtonsoft.Json
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, settings);
return SerializeObject(value, Formatting.None, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, JsonSerializerSettings settings)
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
//jsonWriter.Formatting = Formatting.Indented;
jsonWriter.Formatting = formatting;
jsonSerializer.Serialize(jsonWriter, value);
}
+6 -1
View File
@@ -159,6 +159,11 @@ namespace Newtonsoft.Json
}
/// <summary>
/// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/> objects.
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns></returns>
public static JsonSerializer Create(JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = new JsonSerializer();
@@ -729,7 +734,7 @@ namespace Newtonsoft.Json
}
else if (value is JsonRaw)
{
writer.WriteRaw(((JsonRaw)value).Content, true);
writer.WriteRawValue(((JsonRaw)value).Content);
}
else
{
@@ -6,6 +6,9 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies the settings on a <see cref="JsonSerializer"/> object.
/// </summary>
public class JsonSerializerSettings
{
internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error;
@@ -14,13 +17,40 @@ namespace Newtonsoft.Json
internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include;
internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto;
/// <summary>
/// Gets or sets how reference loops (e.g. a class referencing itself) is handled.
/// </summary>
/// <value>Reference loop handling.</value>
public ReferenceLoopHandling ReferenceLoopHandling { get; set; }
/// <summary>
/// Gets or sets how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
/// </summary>
/// <value>Missing member handling.</value>
public MissingMemberHandling MissingMemberHandling { get; set; }
/// <summary>
/// Gets or sets how objects are created during deserialization.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling ObjectCreationHandling { get; set; }
/// <summary>
/// Gets or sets how null values are handled during serialization and deserialization.
/// </summary>
/// <value>Null value handling.</value>
public NullValueHandling NullValueHandling { get; set; }
/// <summary>
/// Gets or sets how null default are handled during serialization and deserialization.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling DefaultValueHandling { get; set; }
/// <summary>
/// Gets or sets a collection <see cref="JsonConverter"/> that will be used during serialization.
/// </summary>
/// <value>The converters.</value>
public IList<JsonConverter> Converters { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializerSettings"/> class.
/// </summary>
public JsonSerializerSettings()
{
ReferenceLoopHandling = DefaultReferenceLoopHandling;
+9 -6
View File
@@ -372,7 +372,7 @@ namespace Newtonsoft.Json
WriteValue((DateTime)reader.Value);
break;
case JsonToken.Raw:
WriteRaw((string)reader.Value, true);
WriteRawValue((string)reader.Value);
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type.");
@@ -608,19 +608,22 @@ namespace Newtonsoft.Json
}
/// <summary>
/// Writes raw JSON.
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
}
internal void WriteRaw(string json, bool autoCompleteValue)
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
WriteRaw(json);
// hack
if (autoCompleteValue)
AutoComplete(JsonToken.Undefined);
// hack. want writer to change state as if a value had been written
AutoComplete(JsonToken.Undefined);
}
/// <summary>
+1 -1
View File
@@ -106,7 +106,7 @@ namespace Newtonsoft.Json.Linq
}
if (reader.TokenType != JsonToken.StartArray)
{
throw new Exception("Current JsonReader item is not an object.");
throw new Exception("Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
else
{
+1 -1
View File
@@ -193,7 +193,7 @@ namespace Newtonsoft.Json.Linq
}
if (reader.TokenType != JsonToken.StartObject)
{
throw new Exception("Current JsonReader item is not an object.");
throw new Exception("Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
else
{
@@ -43,6 +43,7 @@
<FileAlignment>512</FileAlignment>
<WarningLevel>4</WarningLevel>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<DocumentationFile>bin\Release\Newtonsoft.Json.Compact.XML</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
@@ -48,170 +48,11 @@
<Reference Include="System.Windows.Browser" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Newtonsoft.Json\Converters\HtmlColorConverter.cs">
<Link>Converters\HtmlColorConverter.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Converters\IsoDateTimeConverter.cs">
<Link>Converters\IsoDateTimeConverter.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Converters\JavaScriptDateTimeConverter.cs">
<Link>Converters\JavaScriptDateTimeConverter.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Converters\JsonDateTimeSerializationMode.cs">
<Link>Converters\JsonDateTimeSerializationMode.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Converters\XmlNodeConverter.cs">
<Link>Converters\XmlNodeConverter.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JavaScriptConvert.cs">
<Link>JavaScriptConvert.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonConverter.cs">
<Link>JsonConverter.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonConverterAttribute.cs">
<Link>JsonConverterAttribute.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonConverterCollection.cs">
<Link>JsonConverterCollection.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonIgnoreAttribute.cs">
<Link>JsonIgnoreAttribute.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonObjectAttribute.cs">
<Link>JsonObjectAttribute.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonPropertyAttribute.cs">
<Link>JsonPropertyAttribute.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonReader.cs">
<Link>JsonReader.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonReaderException.cs">
<Link>JsonReaderException.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonSerializationException.cs">
<Link>JsonSerializationException.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonSerializer.cs">
<Link>JsonSerializer.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonTextReader.cs">
<Link>JsonTextReader.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonTextWriter.cs">
<Link>JsonTextWriter.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonToken.cs">
<Link>JsonToken.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonWriter.cs">
<Link>JsonWriter.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\JsonWriterException.cs">
<Link>JsonWriterException.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\Extensions.cs">
<Link>Linq\Extensions.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JArray.cs">
<Link>Linq\JArray.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JConstructor.cs">
<Link>Linq\JConstructor.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JContainer.cs">
<Link>Linq\JContainer.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JEnumerable.cs">
<Link>Linq\JEnumerable.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JObject.cs">
<Link>Linq\JObject.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JProperty.cs">
<Link>Linq\JProperty.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JsonTokenReader.cs">
<Link>Linq\JsonTokenReader.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JsonTokenType.cs">
<Link>Linq\JsonTokenType.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JsonTokenWriter.cs">
<Link>Linq\JsonTokenWriter.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JToken.cs">
<Link>Linq\JToken.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JTokenEqualityComparer.cs">
<Link>Linq\JTokenEqualityComparer.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Linq\JValue.cs">
<Link>Linq\JValue.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\MemberMapping.cs">
<Link>MemberMapping.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\MemberMappingCollection.cs">
<Link>MemberMappingCollection.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\MemberSerialization.cs">
<Link>MemberSerialization.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\MissingMemberHandling.cs">
<Link>MissingMemberHandling.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\NullValueHandling.cs">
<Link>NullValueHandling.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\ObjectCreationHandling.cs">
<Link>ObjectCreationHandling.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\ReferenceLoopHandling.cs">
<Link>ReferenceLoopHandling.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\StringBuffer.cs">
<Link>StringBuffer.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\CollectionUtils.cs">
<Link>Utilities\CollectionUtils.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\ConvertUtils.cs">
<Link>Utilities\ConvertUtils.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\DateTimeUtils.cs">
<Link>Utilities\DateTimeUtils.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\DictionaryWrapper.cs">
<Link>Utilities\DictionaryWrapper.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\JavaScriptUtils.cs">
<Link>Utilities\JavaScriptUtils.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\ListWrapper.cs">
<Link>Utilities\ListWrapper.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\MathUtils.cs">
<Link>Utilities\MathUtils.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\MiscellaneousUtils.cs">
<Link>Utilities\MiscellaneousUtils.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\ReflectionUtils.cs">
<Link>Utilities\ReflectionUtils.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\StringUtils.cs">
<Link>Utilities\StringUtils.cs</Link>
</Compile>
<Compile Include="..\Newtonsoft.Json\Utilities\ValidationUtils.cs">
<Link>Utilities\ValidationUtils.cs</Link>
</Compile>
<Compile Include="Converters\HtmlColorConverter.cs" />
<Compile Include="Converters\IsoDateTimeConverter.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverter.cs" />
<Compile Include="Converters\JsonDateTimeSerializationMode.cs" />
<Compile Include="Converters\XmlNodeConverter.cs" />
<Compile Include="Converters\HtmlColorConverter.cs" />
<Compile Include="DefaultValueHandling.cs" />
<Compile Include="JavaScriptConvert.cs" />
<Compile Include="JsonConverter.cs" />
+13 -3
View File
@@ -27,16 +27,26 @@ using System.Security;
// associated with an assembly.
#if SILVERLIGHT
[assembly: AssemblyTitle("Newtonsoft Json.NET Silverlight")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests.Silverlight")]
#elif PocketPC
[assembly: AssemblyTitle("Newtonsoft Json.NET Compact")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests.Compact")]
#else
[assembly: AssemblyTitle("Newtonsoft Json.NET")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests")]
[assembly: AllowPartiallyTrustedCallers]
#endif
#if !SIGNED
#if SILVERLIGHT
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests.Silverlight")]
#elif PocketPC
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests.Compact")]
#else
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests")]
#endif
#endif
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]