Specified CultureInfo when converting to and from strings across Json.NET.

Fixes:
Clone JToken when adding token with a parent to a new token.
This commit is contained in:
JamesNK
2008-03-16 03:04:28 +00:00
parent 010177a27d
commit 3d150fe2c3
32 changed files with 512 additions and 162 deletions
+88
View File
@@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using System.Xml.Linq;
namespace Newtonsoft.Json.Tests
{
public class JTokenTests : TestFixtureBase
{
[Test]
public void Parent()
{
JValue v = new JValue(new DateTime(2000, 12, 20));
Assert.AreEqual(null, v.Parent);
JObject o =
new JObject(
new JProperty("Test1", v),
new JProperty("Test2", "Test2Value"),
new JProperty("Test3", "Test3Value"),
new JProperty("Test4", null)
);
Assert.AreEqual(o.Property("Test1"), v.Parent);
JProperty p = new JProperty("NewProperty", v);
// existing value should still have same parent
Assert.AreEqual(o.Property("Test1"), v.Parent);
// new value should be cloned
Assert.AreNotEqual(p.Value, v);
Assert.AreEqual((DateTime)p.Value, (DateTime)v.Value);
Assert.AreEqual(v, o["Test1"]);
XText t = new XText("XText");
Assert.AreEqual(null, t.Parent);
Assert.AreEqual(null, o.Parent);
JProperty o1 = new JProperty("O1", o);
Assert.AreEqual(o, o1.Value);
Assert.AreNotEqual(null, o.Parent);
JProperty o2 = new JProperty("O2", o);
Assert.AreNotEqual(o1.Value, o2.Value);
Assert.AreEqual(o1.Value.Children().Count(), o2.Value.Children().Count());
Assert.AreEqual(false, JToken.DeepEquals(o1, o2));
Assert.AreEqual(true, JToken.DeepEquals(o1.Value, o2.Value));
}
[Test]
public void Children()
{
JArray a =
new JArray(
5,
new JArray(1, 2, 3),
new JArray(1, 2, 3),
new JArray(1, 2, 3)
);
Assert.AreEqual(4, a.Count());
Assert.AreEqual(3, a.Children<JArray>().Count());
}
[Test]
public void Casting()
{
//JToken t = new JValue(new DateTime(2000, 12, 20));
//DateTime d = (DateTime)t;
Assert.AreEqual(new DateTime(2000, 12, 20), (DateTime)new JValue(new DateTime(2000, 12, 20)));
Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.AreEqual(true, (bool)new JValue(true));
Assert.AreEqual(true, (bool?)new JValue(true));
Assert.AreEqual(null, (bool?)((JValue)null));
Assert.AreEqual(null, (bool?)JValue.Null);
Assert.AreEqual(null, (bool?)JValue.Undefined);
}
}
}
@@ -66,5 +66,27 @@ now brown cow?", '"', true);
result = JavaScriptUtils.ToEscapedJavaScriptString(@"Fred's ""cat"".", '\'', true);
Assert.AreEqual(result, @"'Fred\'s ""cat"".'");
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.")]
public void ToStringInvalid()
{
JavaScriptConvert.ToString(new Version());
}
[Test]
public void GuidToString()
{
Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
string json = JavaScriptConvert.ToString(guid);
Assert.AreEqual(@"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""", json);
}
[Test]
public void EnumToString()
{
string json = JavaScriptConvert.ToString(StringComparison.CurrentCultureIgnoreCase);
Assert.AreEqual("1", json);
}
}
}
+46 -19
View File
@@ -118,6 +118,11 @@ namespace Newtonsoft.Json.Tests
White
}
public class ClassWithGuid
{
public Guid GuidField;
}
public class ClassWithArray
{
private readonly IList<long> bar;
@@ -135,13 +140,31 @@ namespace Newtonsoft.Json.Tests
set { foo = value; }
}
[JsonProperty("bar")]
[JsonProperty(PropertyName = "bar")]
public IList<long> Bar
{
get { return bar; }
}
}
public class ConverableMembers
{
public string String = "string";
public int Int32 = int.MaxValue;
public uint UInt32 = uint.MaxValue;
public byte Byte = byte.MaxValue;
public sbyte SByte = sbyte.MaxValue;
public short Short = short.MaxValue;
public ushort UShort = ushort.MaxValue;
public long Long = long.MaxValue;
public ulong ULong = long.MaxValue;
public double Double = double.MaxValue;
public float Float = float.MaxValue;
public DBNull DBNull = DBNull.Value;
public bool Bool = true;
public char Char = '\0';
}
public class JsonSerializerTest : TestFixtureBase
{
[Test]
@@ -872,24 +895,6 @@ keyword such as type of business.""
Assert.AreEqual(3, wibbleOut.Bar[4]);
}
public class ConverableMembers
{
public string String = "string";
public int Int32 = int.MaxValue;
public uint UInt32 = uint.MaxValue;
public byte Byte = byte.MaxValue;
public sbyte SByte = sbyte.MaxValue;
public short Short = short.MaxValue;
public ushort UShort = ushort.MaxValue;
public long Long = long.MaxValue;
public ulong ULong = long.MaxValue;
public double Double = double.MaxValue;
public float Float = float.MaxValue;
public DBNull DBNull = DBNull.Value;
public bool Bool = true;
public char Char = '\0';
}
[Test]
public void SerializeConverableObjects()
{
@@ -914,5 +919,27 @@ keyword such as type of business.""
string json = JavaScriptConvert.SerializeObject(s);
Assert.AreEqual("[3,2,1]", json);
}
[Test]
public void GuidTest()
{
Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
string json = JavaScriptConvert.SerializeObject(new ClassWithGuid { GuidField = guid });
Assert.AreEqual(@"{""GuidField"":""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""}", json);
ClassWithGuid c = JavaScriptConvert.DeserializeObject<ClassWithGuid>(json);
Assert.AreEqual(guid, c.GuidField);
}
[Test]
public void EnumTest()
{
string json = JavaScriptConvert.SerializeObject(StringComparison.CurrentCultureIgnoreCase);
Assert.AreEqual(@"1", json);
StringComparison s = JavaScriptConvert.DeserializeObject<StringComparison>(json);
Assert.AreEqual(StringComparison.CurrentCultureIgnoreCase, s);
}
}
}
+3 -3
View File
@@ -75,7 +75,7 @@ namespace Newtonsoft.Json.Tests
string json = @"[0,1,2,3,4,5,6,7,8,9]";
JArray a = JArray.Parse(json);
List<int> list = a.Children<int>().ToList();
List<int> list = a.Values<int>().ToList();
List<int> expected = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
@@ -345,7 +345,7 @@ keyword such as type of business.""
{
List<Post> posts = GetPosts();
JObject rss =
JObject rss =
new JObject(
new JProperty("channel",
new JObject(
@@ -549,7 +549,7 @@ keyword such as type of business.""
JObject o = JObject.FromObject(new
{
channel = new
channel = new
{
title = "James Newton-King",
link = "http://james.newtonking.com",
@@ -64,6 +64,9 @@
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="DateTimeTestClass.cs" />
@@ -75,6 +78,7 @@
<Compile Include="JsonTextWriterTest.cs" />
<Compile Include="JsonTokenReaderTest.cs" />
<Compile Include="JsonTokenWriterTest.cs" />
<Compile Include="JTokenTests.cs" />
<Compile Include="LinqToJsonTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TestFixtureBase.cs" />
@@ -41,5 +41,10 @@ namespace Newtonsoft.Json.Converters
{
return typeof(Color).IsAssignableFrom(valueType);
}
public override object ReadJson(JsonReader reader, Type objectType)
{
throw new NotImplementedException();
}
}
}
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
@@ -11,13 +12,6 @@ namespace Newtonsoft.Json.Converters
private const string DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK";
private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
//private bool _forceUniversalTime;
//public bool ForceUniversalTime
//{
// get { return _forceUniversalTime; }
// set { _forceUniversalTime = value; }
//}
public DateTimeStyles DateTimeStyles
{
@@ -55,7 +49,7 @@ namespace Newtonsoft.Json.Converters
public override object ReadJson(JsonReader reader, Type objectType)
{
if (reader.TokenType != JsonToken.String)
throw new Exception(string.Format("Unexpected token parsing date. Expected String, got {0}.", reader.TokenType));
throw new Exception("Unexpected token parsing date. Expected String, got {0}.".FormatWith(reader.TokenType));
string dateText = reader.Value.ToString();
@@ -71,4 +65,4 @@ namespace Newtonsoft.Json.Converters
|| typeof(DateTimeOffset).IsAssignableFrom(objectType));
}
}
}
}
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
@@ -33,12 +34,12 @@ namespace Newtonsoft.Json.Converters
public override object ReadJson(JsonReader reader, Type objectType)
{
if (reader.TokenType != JsonToken.StartConstructor || string.Compare(reader.Value.ToString(), "Date", StringComparison.Ordinal) != 0)
throw new Exception(string.Format("Unexpected token or value when parsing date. Token: {0}, Value: {1}", reader.TokenType, reader.Value));
throw new Exception("Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(reader.TokenType, reader.Value));
reader.Read();
if (reader.TokenType != JsonToken.Integer)
throw new Exception(string.Format("Unexpected token parsing date. Expected Integer, got {0}.", reader.TokenType));
throw new Exception("Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(reader.TokenType));
long ticks = (long)reader.Value;
@@ -47,7 +48,7 @@ namespace Newtonsoft.Json.Converters
reader.Read();
if (reader.TokenType != JsonToken.EndConstructor)
throw new Exception(string.Format("Unexpected token parsing date. Expected EndConstructor, got {0}.", reader.TokenType));
throw new Exception("Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(reader.TokenType));
if (objectType == typeof(DateTimeOffset))
return new DateTimeOffset(d);
@@ -61,4 +62,4 @@ namespace Newtonsoft.Json.Converters
|| typeof(DateTimeOffset).IsAssignableFrom(objectType));
}
}
}
}
+7 -3
View File
@@ -127,7 +127,7 @@ namespace Newtonsoft.Json
case DateTimeKind.Local:
case DateTimeKind.Unspecified:
TimeSpan utcOffset = value.Offset;
offset = utcOffset.Hours.ToString("+00;-00") + utcOffset.Minutes.ToString("00;00");
offset = utcOffset.Hours.ToString("+00;-00", CultureInfo.InvariantCulture) + utcOffset.Minutes.ToString("00;00", CultureInfo.InvariantCulture);
break;
default:
offset = string.Empty;
@@ -182,7 +182,7 @@ namespace Newtonsoft.Json
/// <returns>A Json string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString();
return Enum.Format(value.GetType(), value, "D");
}
/// <summary>
@@ -379,8 +379,12 @@ namespace Newtonsoft.Json
{
return ToString((DateTimeOffset)value);
}
else if (value is Guid)
{
return ToString((Guid)value);
}
throw new ArgumentException(string.Format("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.", value.GetType()));
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(value.GetType()));
}
/// <summary>
+3 -12
View File
@@ -26,23 +26,14 @@
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
public abstract class JsonConverter
{
public virtual void WriteJson(JsonWriter writer, object value)
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, value);
}
public virtual object ReadJson(JsonReader reader, Type objectType)
{
throw new NotImplementedException(string.Format("{0} has not overriden the ReadJson method.", GetType().Name));
}
public abstract void WriteJson(JsonWriter writer, object value);
public abstract object ReadJson(JsonReader reader, Type objectType);
public abstract bool CanConvert(Type objectType);
}
}
@@ -13,6 +13,10 @@ namespace Newtonsoft.Json
set { _propertyName = value; }
}
public JsonPropertyAttribute()
{
}
public JsonPropertyAttribute(string propertyName)
{
_propertyName = propertyName;
+2 -1
View File
@@ -30,6 +30,7 @@ using System.IO;
using System.Xml;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
@@ -238,7 +239,7 @@ namespace Newtonsoft.Json
JsonTokenType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
throw new JsonReaderException(string.Format("JsonToken {0} is not valid for closing JsonType {1}.", endToken, currentObject));
throw new JsonReaderException("JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(endToken, currentObject));
}
protected void SetStateBasedOnCurrent()
+5 -5
View File
@@ -290,7 +290,7 @@ namespace Newtonsoft.Json
return new DateTimeOffset((DateTime)value);
if (!targetType.IsAssignableFrom(valueType))
throw new InvalidOperationException(string.Format("Cannot convert object of type '{0}' to type '{1}'", value.GetType(), targetType));
throw new InvalidOperationException("Cannot convert object of type '{0}' to type '{1}'".FormatWith(value.GetType(), targetType));
return value;
}
@@ -348,7 +348,7 @@ namespace Newtonsoft.Json
private void SetObjectMember(JsonReader reader, object target, Type targetType, string memberName)
{
if (!reader.Read())
throw new JsonSerializationException(string.Format("Unexpected end when setting {0}'s value.", memberName));
throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(memberName));
MemberMappingCollection memberMappings = GetMemberMappings(targetType);
Type memberType;
@@ -392,7 +392,7 @@ namespace Newtonsoft.Json
else
{
if (_missingMemberHandling == MissingMemberHandling.Error)
throw new JsonSerializationException(string.Format("Could not find member '{0}' on object of type '{1}'", memberName, targetType.GetType().Name));
throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(memberName, targetType.GetType().Name));
}
}
@@ -490,7 +490,7 @@ namespace Newtonsoft.Json
.SingleOrDefault();
if (!reader.Read())
throw new JsonSerializationException(string.Format("Unexpected end when setting {0}'s value.", memberName));
throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(memberName));
if (matchingConstructorParameter != null)
constructorParameters[matchingConstructorParameter] = CreateObject(reader, matchingConstructorParameter.ParameterType, null);
@@ -710,7 +710,7 @@ namespace Newtonsoft.Json
// continue
break;
default:
throw new InvalidOperationException(string.Format("Unexpected ReferenceLoopHandling value: '{0}'", _referenceLoopHandling));
throw new InvalidOperationException("Unexpected ReferenceLoopHandling value: '{0}'".FormatWith(_referenceLoopHandling));
}
}
+1 -1
View File
@@ -193,7 +193,7 @@ namespace Newtonsoft.Json
value = value.Substring(0, index);
}
long javaScriptTicks = long.Parse(value);
long javaScriptTicks = long.Parse(value, CultureInfo.InvariantCulture);
DateTime utcDateTime = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
DateTime dateTime;
+2 -2
View File
@@ -139,7 +139,7 @@ namespace Newtonsoft.Json
{
get { return _top; }
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
@@ -513,7 +513,7 @@ namespace Newtonsoft.Json
State newState = stateArray[token, (int)_currentState];
if (newState == State.Error)
throw new JsonWriterException(string.Format("Token {0} in state {1} would result in an invalid JavaScript object.", tokenBeingWritten.ToString(), _currentState.ToString()));
throw new JsonWriterException("Token {0} in state {1} would result in an invalid JavaScript object.".FormatWith(tokenBeingWritten.ToString(), _currentState.ToString()));
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
+9 -8
View File
@@ -29,6 +29,7 @@ using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Collections;
using System.Globalization;
namespace Newtonsoft.Json.Linq
{
@@ -125,15 +126,15 @@ namespace Newtonsoft.Json.Linq
//List<U> s = childrenValues.Convert<JToken, U>().ToList();
//return childrenValues.Convert<JToken, U>();
// return source.SelectMany(d => d.Properties())
//.Where(p => string.Compare(p.Name, name, StringComparison.Ordinal) == 0)
//.Select(p => p.Value)
//.Convert<JToken, T>();
// return source.SelectMany(d => d.Properties())
//.Where(p => string.Compare(p.Name, name, StringComparison.Ordinal) == 0)
//.Select(p => p.Value)
//.Convert<JToken, T>();
}
//TODO
//public static IEnumerable<T> InDocumentOrder<T>(this IEnumerable<T> source) where T : JObject;
//public static IEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JToken
//{
// ValidationUtils.ArgumentNotNull(source, "source");
@@ -181,9 +182,9 @@ namespace Newtonsoft.Json.Linq
JValue value = token as JValue;
if (value == null)
throw new InvalidCastException(string.Format("Cannot cast {0} to {1}.", token.GetType(), typeof(T)));
throw new InvalidCastException("Cannot cast {0} to {1}.".FormatWith(token.GetType(), typeof(T)));
return (U)System.Convert.ChangeType(value.Value, typeof(U));
return (U)System.Convert.ChangeType(value.Value, typeof(U), CultureInfo.InvariantCulture);
}
}
@@ -193,4 +194,4 @@ namespace Newtonsoft.Json.Linq
}
}
}
+19 -3
View File
@@ -43,6 +43,11 @@ namespace Newtonsoft.Json.Linq
{
}
public JArray(JArray other)
: base(other)
{
}
public JArray(params object[] content)
: this((object)content)
{
@@ -53,6 +58,17 @@ namespace Newtonsoft.Json.Linq
Add(content);
}
internal override bool DeepEquals(JToken node)
{
JArray t = node as JArray;
return (t != null && ContentsEqual(t));
}
internal override JToken CloneNode()
{
return new JArray(this);
}
public int Count()
{
return Children().Count();
@@ -93,7 +109,7 @@ namespace Newtonsoft.Json.Linq
ValidationUtils.ArgumentNotNull(o, "o");
if (o.Type == JsonTokenType.Property)
throw new ArgumentException(string.Format("An item of type {0} cannot be added to content.", o.Type));
throw new ArgumentException("An item of type {0} cannot be added to content.".FormatWith(o.Type));
}
public static JArray FromObject(object o)
@@ -101,7 +117,7 @@ namespace Newtonsoft.Json.Linq
JToken token = FromObjectInternal(o);
if (token.Type != JsonTokenType.Array)
throw new ArgumentException(string.Format("Object serialized to {0}. JArray instance expected.", token.Type));
throw new ArgumentException("Object serialized to {0}. JArray instance expected.".FormatWith(token.Type));
return (JArray)token;
}
@@ -125,7 +141,7 @@ namespace Newtonsoft.Json.Linq
ValidationUtils.ArgumentNotNull(key, "o");
if (!(key is int))
throw new ArgumentException(string.Format("Accessed JArray values with invalid key value: {0}. Array position index expected.", MiscellaneousUtils.ToString(key)));
throw new ArgumentException("Accessed JArray values with invalid key value: {0}. Array position index expected.".FormatWith(MiscellaneousUtils.ToString(key)));
return GetIndex(this, (int)key);
}
+18 -2
View File
@@ -50,6 +50,11 @@ namespace Newtonsoft.Json.Linq
{
}
public JConstructor(JConstructor other)
: base(other)
{
}
public JConstructor(string name, params object[] content)
: this(name, (object)content)
{
@@ -66,6 +71,17 @@ namespace Newtonsoft.Json.Linq
_name = name;
}
internal override bool DeepEquals(JToken node)
{
JConstructor c = node as JConstructor;
return (c != null && _name == c.Name && ContentsEqual(c));
}
internal override JToken CloneNode()
{
return new JConstructor(this);
}
internal override void ValidateObject(JToken o, JToken previous)
{
ValidationUtils.ArgumentNotNull(o, "o");
@@ -73,7 +89,7 @@ namespace Newtonsoft.Json.Linq
switch (o.Type)
{
case JsonTokenType.Property:
throw new ArgumentException(string.Format("An item of type {0} cannot be added to content.", o.Type));
throw new ArgumentException("An item of type {0} cannot be added to content.".FormatWith(o.Type));
}
}
@@ -96,7 +112,7 @@ namespace Newtonsoft.Json.Linq
ValidationUtils.ArgumentNotNull(key, "o");
if (!(key is int))
throw new ArgumentException(string.Format("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.", MiscellaneousUtils.ToString(key)));
throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(MiscellaneousUtils.ToString(key)));
return GetIndex(this, (int)key);
}
+79 -7
View File
@@ -29,6 +29,7 @@ using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Collections;
using System.Diagnostics;
namespace Newtonsoft.Json.Linq
{
@@ -42,6 +43,52 @@ namespace Newtonsoft.Json.Linq
set { _content = value; }
}
protected JContainer()
{
}
protected JContainer(JContainer other)
{
ValidationUtils.ArgumentNotNull(other, "c");
JToken content = other.Last;
if (content != null)
{
do
{
content = content.Next;
Add(content.CloneNode());
}
while (content != other.Last);
}
}
internal bool ContentsEqual(JContainer container)
{
JToken t1 = First;
JToken t2 = container.First;
if (t1 == t2)
return true;
do
{
if (t1 == null && t2 == null)
return true;
if (t1 != null && t2 != null && t1.DeepEquals(t2))
{
t1 = (t1 != Last) ? t1.Next : null;
t2 = (t2 != container.Last) ? t2.Next : null;
}
else
{
return false;
}
}
while (true);
}
public override JToken First
{
get
@@ -55,6 +102,7 @@ namespace Newtonsoft.Json.Linq
public override JToken Last
{
[DebuggerStepThrough]
get { return _content; }
}
@@ -76,17 +124,17 @@ namespace Newtonsoft.Json.Linq
} while ((current = current.Next) != first);
}
public override IEnumerable<T> Children<T>()
public override IEnumerable<T> Values<T>()
{
return Children().Convert<JToken, T>();
}
public override T Value<T>(object key)
{
JToken token = this[key];
//public override T Value<T>(object key)
//{
// JToken token = this[key];
return Extensions.Convert<JToken, T>(token);
}
// return Extensions.Convert<JToken, T>(token);
//}
public IEnumerable<JToken> Descendants()
{
@@ -144,6 +192,25 @@ namespace Newtonsoft.Json.Linq
{
JToken o = CreateFromContent(content);
ValidateToken(o);
if (o.Parent != null)
{
o = o.CloneNode();
}
else
{
JContainer parent = this;
while (parent.Parent != null)
{
parent = parent.Parent;
}
if (o == parent)
{
o = o.CloneNode();
}
}
JToken last = Last;
JToken next = First ?? o;
@@ -156,6 +223,11 @@ namespace Newtonsoft.Json.Linq
}
}
internal virtual void ValidateToken(JToken o)
{
//throw new NotImplementedException();
}
public void AddFirst(object content)
{
JToken o = CreateFromContent(content);
@@ -319,7 +391,7 @@ namespace Newtonsoft.Json.Linq
parent = property;
break;
default:
throw new InvalidOperationException(string.Format("The JsonReader should not be on a token of type {0}.", r.TokenType));
throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(r.TokenType));
}
}
while (r.Read());
+22 -5
View File
@@ -38,7 +38,13 @@ namespace Newtonsoft.Json.Linq
{
}
public JObject(params object[] content) : this((object)content)
public JObject(JObject other)
: base(other)
{
}
public JObject(params object[] content)
: this((object)content)
{
}
@@ -47,6 +53,17 @@ namespace Newtonsoft.Json.Linq
Add(content);
}
internal override bool DeepEquals(JToken node)
{
JObject t = node as JObject;
return (t != null && ContentsEqual(t));
}
internal override JToken CloneNode()
{
return new JObject(this);
}
public override JsonTokenType Type
{
get { return JsonTokenType.Object; }
@@ -74,7 +91,7 @@ namespace Newtonsoft.Json.Linq
ValidationUtils.ArgumentNotNull(content, "content");
if (!(content is JProperty) && !IsMultiContent(content))
throw new ArgumentException(string.Format("Error adding {0} to JObject. JObject only supports JProperty content.", content.GetType().Name));
throw new ArgumentException("Error adding {0} to JObject. JObject only supports JProperty content.".FormatWith(content.GetType().Name));
base.Add(content);
}
@@ -87,7 +104,7 @@ namespace Newtonsoft.Json.Linq
string propertyName = key as string;
if (propertyName == null)
throw new ArgumentException(string.Format("Accessed JObject values with invalid key value: {0}. Object property name expected.", MiscellaneousUtils.ToString(key)));
throw new ArgumentException("Accessed JObject values with invalid key value: {0}. Object property name expected.".FormatWith(MiscellaneousUtils.ToString(key)));
JProperty property = Property(propertyName);
@@ -132,7 +149,7 @@ namespace Newtonsoft.Json.Linq
JToken token = FromObjectInternal(o);
if (token.Type != JsonTokenType.Object)
throw new ArgumentException(string.Format("Object serialized to {0}. JObject instance expected.", token.Type));
throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(token.Type));
return (JObject)token;
}
@@ -142,7 +159,7 @@ namespace Newtonsoft.Json.Linq
ValidationUtils.ArgumentNotNull(o, "o");
if (o.Type != JsonTokenType.Property)
throw new ArgumentException(string.Format("An item of type {0} cannot be added to content.", o.Type));
throw new ArgumentException("An item of type {0} cannot be added to content.".FormatWith(o.Type));
}
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
+23 -2
View File
@@ -28,6 +28,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Diagnostics;
namespace Newtonsoft.Json.Linq
{
@@ -37,11 +38,13 @@ namespace Newtonsoft.Json.Linq
public string Name
{
[DebuggerStepThrough]
get { return _name; }
}
}
public JToken Value
{
[DebuggerStepThrough]
get { return Last; }
set
{
@@ -49,8 +52,26 @@ namespace Newtonsoft.Json.Linq
}
}
public JProperty(JProperty other)
: base(other)
{
_name = other.Name;
}
internal override bool DeepEquals(JToken node)
{
JProperty t = node as JProperty;
return (t != null && _name == t.Name && ContentsEqual(t));
}
internal override JToken CloneNode()
{
return new JProperty(this);
}
public override JsonTokenType Type
{
[DebuggerStepThrough]
get { return JsonTokenType.Property; }
}
@@ -74,7 +95,7 @@ namespace Newtonsoft.Json.Linq
ValidationUtils.ArgumentNotNull(o, "o");
if (o.Type == JsonTokenType.Property)
throw new ArgumentException(string.Format("An item of type {0} cannot be added to content.", o.Type));
throw new ArgumentException("An item of type {0} cannot be added to content.".FormatWith(o.Type));
}
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
+64 -36
View File
@@ -28,6 +28,9 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json.Utilities;
using System.Diagnostics;
using System.Globalization;
namespace Newtonsoft.Json.Linq
{
@@ -38,6 +41,7 @@ namespace Newtonsoft.Json.Linq
public JContainer Parent
{
[DebuggerStepThrough]
get { return _parent; }
internal set { _parent = value; }
}
@@ -47,8 +51,16 @@ namespace Newtonsoft.Json.Linq
get { return null; }
}
internal abstract JToken CloneNode();
internal abstract bool DeepEquals(JToken node);
public abstract JsonTokenType Type { get; }
public static bool DeepEquals(JToken t1, JToken t2)
{
return (t1 == t2 || (t1 != null && t2 != null && t1.DeepEquals(t2)));
}
public JToken Next
{
get
@@ -66,14 +78,14 @@ namespace Newtonsoft.Json.Linq
get
{
if (_parent == null)
return null;
return null;
JToken parentNext = ((JToken) _parent.Content).Next;
JToken parentNext = ((JToken)_parent.Content).Next;
JToken parentNextBefore = null;
while (parentNext != this)
{
parentNextBefore = parentNext;
parentNext = parentNext.Next;
parentNextBefore = parentNext;
parentNext = parentNext.Next;
}
return parentNextBefore;
}
@@ -109,34 +121,50 @@ namespace Newtonsoft.Json.Linq
public virtual JToken this[object key]
{
get { return null; }
get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(GetType())); }
}
public virtual T Value<T>(object key)
{
return default(T);
JToken token = this[key];
return Extensions.Convert<JToken, T>(token);
}
public virtual JToken First
{
get { return null; }
get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(GetType())); }
//get { return null; }
}
public virtual JToken Last
{
get { return null; }
get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(GetType())); }
//get { return null; }
}
public virtual JEnumerable<JToken> Children()
{
return JEnumerable<JToken>.Empty;
throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(GetType()));
//return JEnumerable<JToken>.Empty;
}
public virtual IEnumerable<T> Children<T>()
public JEnumerable<T> Children<T>() where T : JToken
{
return Enumerable.Empty<T>();
return new JEnumerable<T>(Children().OfType<T>());
}
public virtual IEnumerable<T> Values<T>()
{
throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(GetType()));
}
//public virtual IEnumerable<T> Children<T>()
// {
// throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(GetType()));
// //return Enumerable.Empty<T>();
// }
public void Remove()
{
if (_parent == null)
@@ -158,7 +186,7 @@ namespace Newtonsoft.Json.Linq
private string ToString(params JsonConverter[] converters)
{
using (StringWriter sw = new StringWriter())
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
{
JsonTextWriter jw = new JsonTextWriter(sw);
jw.Formatting = Formatting.Indented;
@@ -217,7 +245,7 @@ namespace Newtonsoft.Json.Linq
{
JValue v = EnsureValue(value);
if (v == null || !ValidateBoolean(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Boolean.", v.Type));
throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(v.Type));
return (bool)v.Value;
}
@@ -226,7 +254,7 @@ namespace Newtonsoft.Json.Linq
{
JValue v = EnsureValue(value);
if (v == null || !ValidateDate(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to DateTimeOffset.", v.Type));
throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(v.Type));
return (DateTimeOffset)v.Value;
}
@@ -238,7 +266,7 @@ namespace Newtonsoft.Json.Linq
JValue v = EnsureValue(value);
if (v == null || !ValidateBoolean(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to Boolean.", v.Type));
throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(v.Type));
return (bool?)v.Value;
}
@@ -247,7 +275,7 @@ namespace Newtonsoft.Json.Linq
{
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Int64.", v.Type));
throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(v.Type));
return (long)v.Value;
}
@@ -259,7 +287,7 @@ namespace Newtonsoft.Json.Linq
JValue v = EnsureValue(value);
if (v == null || !ValidateDate(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to DateTime.", v.Type));
throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(v.Type));
return (DateTime?)v.Value;
}
@@ -271,7 +299,7 @@ namespace Newtonsoft.Json.Linq
JValue v = EnsureValue(value);
if (v == null || !ValidateDate(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to DateTimeOffset.", v.Type));
throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(v.Type));
return (DateTimeOffset?)v.Value;
}
@@ -283,7 +311,7 @@ namespace Newtonsoft.Json.Linq
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to Decimal.", v.Type));
throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(v.Type));
return (decimal?)v.Value;
}
@@ -295,7 +323,7 @@ namespace Newtonsoft.Json.Linq
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to Double.", v.Type));
throw new ArgumentException("Can not convert {0} to Double.".FormatWith(v.Type));
return (double?)v.Value;
}
@@ -304,9 +332,9 @@ namespace Newtonsoft.Json.Linq
{
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Int32.", v.Type));
throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(v.Type));
return Convert.ToInt32(v.Value);
return Convert.ToInt32(v.Value, CultureInfo.InvariantCulture);
}
public static explicit operator int?(JToken value)
@@ -316,16 +344,16 @@ namespace Newtonsoft.Json.Linq
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to Int32.", v.Type));
throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(v.Type));
return (v.Value != null) ? (int?)Convert.ToInt32(v.Value) : null;
return (v.Value != null) ? (int?)Convert.ToInt32(v.Value, CultureInfo.InvariantCulture) : null;
}
public static explicit operator DateTime(JToken value)
{
JValue v = EnsureValue(value);
if (v == null || !ValidateDate(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to DateTime.", v.Type));
throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(v.Type));
return (DateTime)v.Value;
}
@@ -334,10 +362,10 @@ namespace Newtonsoft.Json.Linq
{
if (value == null)
return null;
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to Int64.", v.Type));
throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(v.Type));
return (long?)v.Value;
}
@@ -349,7 +377,7 @@ namespace Newtonsoft.Json.Linq
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to Single.", v.Type));
throw new ArgumentException("Can not convert {0} to Single.".FormatWith(v.Type));
return (float?)v.Value;
}
@@ -358,7 +386,7 @@ namespace Newtonsoft.Json.Linq
{
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Decimal.", v.Type));
throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(v.Type));
return (decimal)v.Value;
}
@@ -370,7 +398,7 @@ namespace Newtonsoft.Json.Linq
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to UInt32.", v.Type));
throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(v.Type));
return (uint?)v.Value;
}
@@ -382,7 +410,7 @@ namespace Newtonsoft.Json.Linq
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to UInt64.", v.Type));
throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(v.Type));
return (ulong?)v.Value;
}
@@ -391,7 +419,7 @@ namespace Newtonsoft.Json.Linq
{
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Double.", v.Type));
throw new ArgumentException("Can not convert {0} to Double.".FormatWith(v.Type));
return (double)v.Value;
}
@@ -400,7 +428,7 @@ namespace Newtonsoft.Json.Linq
{
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Single.", v.Type));
throw new ArgumentException("Can not convert {0} to Single.".FormatWith(v.Type));
return (float)v.Value;
}
@@ -412,7 +440,7 @@ namespace Newtonsoft.Json.Linq
JValue v = EnsureValue(value);
if (v == null || !ValidateString(v))
throw new ArgumentException(string.Format("Can not convert {0} to String.", v.Type));
throw new ArgumentException("Can not convert {0} to String.".FormatWith(v.Type));
return (string)v.Value;
}
@@ -421,7 +449,7 @@ namespace Newtonsoft.Json.Linq
{
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to UInt32.", v.Type));
throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(v.Type));
return (uint)v.Value;
}
@@ -430,7 +458,7 @@ namespace Newtonsoft.Json.Linq
{
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to UInt64.", v.Type));
throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(v.Type));
return (ulong)v.Value;
}
+30 -8
View File
@@ -27,6 +27,8 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Linq
{
@@ -44,6 +46,11 @@ namespace Newtonsoft.Json.Linq
_valueType = type;
}
public JValue(JValue value)
: this(value.Value, value.Type)
{
}
public JValue(long value)
: this(value, JsonTokenType.Integer)
{
@@ -69,10 +76,25 @@ namespace Newtonsoft.Json.Linq
{
}
public JValue(object value) : this(value, GetValueType(value))
public JValue(object value)
: this(value, GetValueType(value))
{
}
internal override bool DeepEquals(JToken node)
{
JValue other = node as JValue;
if (other == null)
return false;
return (this == other || (_valueType == other.Type && _value == other.Value));
}
internal override JToken CloneNode()
{
return new JValue(this);
}
public static JValue CreateComment(string value)
{
return new JValue(value, JsonTokenType.Comment);
@@ -94,7 +116,7 @@ namespace Newtonsoft.Json.Linq
else if (value is bool)
return JsonTokenType.Boolean;
throw new ArgumentException(string.Format("Could not determin JSON object type for type {0}.", value.GetType()));
throw new ArgumentException("Could not determin JSON object type for type {0}.".FormatWith(value.GetType()));
}
public override JsonTokenType Type
@@ -132,24 +154,24 @@ namespace Newtonsoft.Json.Linq
writer.WriteComment(_value.ToString());
break;
case JsonTokenType.Integer:
WriteConvertableValue(writer, converters, v => writer.WriteValue(Convert.ToInt64(v)), _value);
WriteConvertableValue(writer, converters, v => writer.WriteValue(Convert.ToInt64(v, CultureInfo.InvariantCulture)), _value);
break;
case JsonTokenType.Float:
WriteConvertableValue(writer, converters, v => writer.WriteValue(Convert.ToDouble(v)), _value);
WriteConvertableValue(writer, converters, v => writer.WriteValue(Convert.ToDouble(v, CultureInfo.InvariantCulture)), _value);
break;
case JsonTokenType.String:
WriteConvertableValue(writer, converters, v => writer.WriteValue(v.ToString()), _value);
break;
case JsonTokenType.Boolean:
WriteConvertableValue(writer, converters, v => writer.WriteValue(Convert.ToBoolean(v)), _value);
WriteConvertableValue(writer, converters, v => writer.WriteValue(Convert.ToBoolean(v, CultureInfo.InvariantCulture)), _value);
break;
case JsonTokenType.Date:
WriteConvertableValue(writer, converters, v =>
WriteConvertableValue(writer, converters, v =>
{
if (v is DateTimeOffset)
writer.WriteValue((DateTimeOffset)v);
else
writer.WriteValue(Convert.ToDateTime(v));
writer.WriteValue(Convert.ToDateTime(v, CultureInfo.InvariantCulture));
}, _value);
break;
case JsonTokenType.Null:
@@ -163,4 +185,4 @@ namespace Newtonsoft.Json.Linq
}
}
}
}
}
@@ -27,6 +27,7 @@ using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
@@ -50,9 +51,7 @@ namespace Newtonsoft.Json
if (!existingMemberMapping.Ignored)
{
throw new JsonSerializationException(
string.Format(
"A member with the name '{0}' already exists on {1}. Use the JsonPropertyAttribute to specify another name.",
memberMapping.MappingName, memberMapping.Member.DeclaringType));
"A member with the name '{0}' already exists on {1}. Use the JsonPropertyAttribute to specify another name.".FormatWith(memberMapping.MappingName, memberMapping.Member.DeclaringType));
}
else
{
File diff suppressed because one or more lines are too long
@@ -315,7 +315,7 @@ namespace Newtonsoft.Json.Utilities
else if (returnDefaultIfEmpty && list.Count == 0)
return default(T);
else
throw new Exception(string.Format("Expected single {0} in list but got {1}.", typeof(T), list.Count));
throw new Exception("Expected single {0} in list but got {1}.".FormatWith(typeof(T), list.Count));
}
#endregion
@@ -389,7 +389,7 @@ namespace Newtonsoft.Json.Utilities
}
else
{
throw new Exception(string.Format("Can not create ListWrapper for type {0}.", list.GetType()));
throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(list.GetType()));
}
}
@@ -418,7 +418,7 @@ namespace Newtonsoft.Json.Utilities
}
else
{
throw new Exception(string.Format("Can not create DictionaryWrapper for type {0}.", dictionary.GetType()));
throw new Exception("Can not create DictionaryWrapper for type {0}.".FormatWith(dictionary.GetType()));
}
}
@@ -459,7 +459,7 @@ namespace Newtonsoft.Json.Utilities
}
if (!suitableConstructor)
throw new Exception(string.Format("Read-only type {0} does not have a public constructor that takes a type that implements {1}.", listType, genericEnumerable));
throw new Exception("Read-only type {0} does not have a public constructor that takes a type that implements {1}.".FormatWith(listType, genericEnumerable));
// can't add or modify a readonly list
// use List<T> and convert once populated
@@ -485,7 +485,7 @@ namespace Newtonsoft.Json.Utilities
}
if (list == null)
throw new Exception(string.Format("Cannot create and populate list type {0}.", listType));
throw new Exception("Cannot create and populate list type {0}.".FormatWith(listType));
populateList(list);
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
@@ -12,7 +13,7 @@ namespace Newtonsoft.Json.Utilities
{
TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(d);
return utcOffset.Hours.ToString("+00;-00") + ":" + utcOffset.Minutes.ToString("00;00");
return utcOffset.Hours.ToString("+00;-00", CultureInfo.InvariantCulture) + ":" + utcOffset.Minutes.ToString("00;00", CultureInfo.InvariantCulture);
}
public static XmlDateTimeSerializationMode ToSerializationMode(DateTimeKind kind)
+1 -1
View File
@@ -261,7 +261,7 @@ namespace Newtonsoft.Json.Utilities
private static void VerifyValueType(object value)
{
if (!IsCompatibleObject(value))
throw new ArgumentException(string.Format("The value '{0}' is not of type '{1}' and cannot be used in this generic collection.", value, typeof(T)), "value");
throw new ArgumentException("The value '{0}' is not of type '{1}' and cannot be used in this generic collection.".FormatWith(value, typeof(T)), "value");
}
private static bool IsCompatibleObject(object value)
@@ -55,7 +55,7 @@ namespace Newtonsoft.Json.Utilities
if (descriptionAttribute != null)
return descriptionAttribute.Description;
else
throw new Exception(string.Format("No DescriptionAttribute on '{0}'.", o.GetType()));
throw new Exception("No DescriptionAttribute on '{0}'.".FormatWith(o.GetType()));
}
public static IList<string> GetDescriptions(IList values)
@@ -106,14 +106,14 @@ namespace Newtonsoft.Json.Utilities
ValidationUtils.ArgumentNotNull(type, "type");
if (type.IsGenericTypeDefinition)
throw new ArgumentException(string.Format("Type {0} is a generic type definition and cannot be instantiated.", type), "type");
throw new ArgumentException("Type {0} is a generic type definition and cannot be instantiated.".FormatWith(type), "type");
if (type.IsClass || type.IsInterface || type == typeof(void))
return null;
else if (type.IsValueType)
return Activator.CreateInstance(type);
else
throw new ArgumentException(string.Format("Type {0} cannot be instantiated.", type), "type");
throw new ArgumentException("Type {0} cannot be instantiated.".FormatWith(type), "type");
}
public static bool IsPropertyIndexed(PropertyInfo property)
@@ -196,7 +196,7 @@ namespace Newtonsoft.Json.Utilities
else if (IsSubClass(type, typeof(IList<>), out genericListType))
{
if (genericListType.IsGenericTypeDefinition)
throw new Exception(string.Format("Type {0} is not a list.", type));
throw new Exception("Type {0} is not a list.".FormatWith(type));
return genericListType.GetGenericArguments()[0];
}
@@ -206,7 +206,7 @@ namespace Newtonsoft.Json.Utilities
}
else
{
throw new Exception(string.Format("Type {0} is not a list.", type));
throw new Exception("Type {0} is not a list.".FormatWith(type));
}
}
@@ -218,7 +218,7 @@ namespace Newtonsoft.Json.Utilities
if (IsSubClass(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType))
{
if (genericDictionaryType.IsGenericTypeDefinition)
throw new Exception(string.Format("Type {0} is not a dictionary.", dictionaryType));
throw new Exception("Type {0} is not a dictionary.".FormatWith(dictionaryType));
Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments();
@@ -234,7 +234,7 @@ namespace Newtonsoft.Json.Utilities
}
else
{
throw new Exception(string.Format("Type {0} is not a dictionary.", dictionaryType));
throw new Exception("Type {0} is not a dictionary.".FormatWith(dictionaryType));
}
}
@@ -289,7 +289,7 @@ namespace Newtonsoft.Json.Utilities
}
else
{
throw new Exception(string.Format("Type {0} is neither a ValueType or a Class.", elementType));
throw new Exception("Type {0} is neither a ValueType or a Class.".FormatWith(elementType));
}
return true;
@@ -387,10 +387,10 @@ namespace Newtonsoft.Json.Utilities
}
catch (TargetParameterCountException e)
{
throw new ArgumentException(string.Format("MemberInfo '{0}' has index parameters", member.Name), "member", e);
throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(member.Name), "member", e);
}
default:
throw new ArgumentException(string.Format("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo", member.Name), "member");
throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(member.Name), "member");
}
}
@@ -414,7 +414,7 @@ namespace Newtonsoft.Json.Utilities
((PropertyInfo)member).SetValue(target, value, null);
break;
default:
throw new ArgumentException(string.Format("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo", member.Name), "member");
throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(member.Name), "member");
}
}
@@ -526,7 +526,7 @@ namespace Newtonsoft.Json.Utilities
{
ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition");
ValidationUtils.ArgumentNotNullOrEmpty<Type>(innerTypes, "innerTypes");
ValidationUtils.ArgumentConditionTrue(genericTypeDefinition.IsGenericTypeDefinition, "genericTypeDefinition", string.Format("Type {0} is not a generic type definition.", genericTypeDefinition));
ValidationUtils.ArgumentConditionTrue(genericTypeDefinition.IsGenericTypeDefinition, "genericTypeDefinition", "Type {0} is not a generic type definition.".FormatWith(genericTypeDefinition));
return genericTypeDefinition.MakeGenericType(innerTypes);
}
+19 -5
View File
@@ -29,6 +29,8 @@ using System.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
@@ -40,6 +42,18 @@ namespace Newtonsoft.Json.Utilities
public const char LineFeed = '\n';
public const char Tab = '\t';
public static string FormatWith(this string format, params object[] args)
{
return FormatWith(format, CultureInfo.InvariantCulture, args);
}
public static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
ValidationUtils.ArgumentNotNull(format, "format");
return string.Format(provider, format, args);
}
/// <summary>
/// Determines whether the string contains white space.
/// </summary>
@@ -190,7 +204,7 @@ namespace Newtonsoft.Json.Utilities
throw new ArgumentException("Must be greater than zero.", "indentation");
StringReader sr = new StringReader(s);
StringWriter sw = new StringWriter();
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line)
{
@@ -229,13 +243,13 @@ namespace Newtonsoft.Json.Utilities
throw new ArgumentNullException("s");
StringReader sr = new StringReader(s);
StringWriter sw = new StringWriter();
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
int lineNumber = 1;
ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line)
{
tw.Write(lineNumber.ToString().PadLeft(4));
tw.Write(lineNumber.ToString(CultureInfo.InvariantCulture).PadLeft(4));
tw.Write(". ");
tw.Write(line);
@@ -354,7 +368,7 @@ namespace Newtonsoft.Json.Utilities
public static StringWriter CreateStringWriter(int capacity)
{
StringBuilder sb = new StringBuilder(capacity);
StringWriter sw = new StringWriter(sb);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
return sw;
}
@@ -369,7 +383,7 @@ namespace Newtonsoft.Json.Utilities
public static string ToCharAsUnicode(char c)
{
using (StringWriter w = new StringWriter())
using (StringWriter w = new StringWriter(CultureInfo.InvariantCulture))
{
WriteCharAsUnicode(w, c);
return w.ToString();
@@ -44,7 +44,7 @@ namespace Newtonsoft.Json.Utilities
throw new ArgumentNullException(parameterName);
if (value.Length == 0)
throw new ArgumentException(string.Format("'{0}' cannot be empty.", parameterName), parameterName);
throw new ArgumentException("'{0}' cannot be empty.".FormatWith(parameterName), parameterName);
}
public static void ArgumentNotNullOrEmptyOrWhitespace(string value, string parameterName)
@@ -52,7 +52,7 @@ namespace Newtonsoft.Json.Utilities
ArgumentNotNullOrEmpty(value, parameterName);
if (StringUtils.IsWhiteSpace(value))
throw new ArgumentException(string.Format("'{0}' cannot only be whitespace.", parameterName), parameterName);
throw new ArgumentException("'{0}' cannot only be whitespace.".FormatWith(parameterName), parameterName);
}
public static void ArgumentTypeIsEnum(Type enumType, string parameterName)
@@ -60,12 +60,12 @@ namespace Newtonsoft.Json.Utilities
ArgumentNotNull(enumType, "enumType");
if (!enumType.IsEnum)
throw new ArgumentException(string.Format("Type {0} is not an Enum.", enumType), parameterName);
throw new ArgumentException("Type {0} is not an Enum.".FormatWith(enumType), parameterName);
}
public static void ArgumentNotNullOrEmpty<T>(ICollection<T> collection, string parameterName)
{
ArgumentNotNullOrEmpty<T>(collection, parameterName, string.Format("Collection '{0}' cannot be empty.", parameterName));
ArgumentNotNullOrEmpty<T>(collection, parameterName, "Collection '{0}' cannot be empty.".FormatWith(parameterName));
}
public static void ArgumentNotNullOrEmpty<T>(ICollection<T> collection, string parameterName, string message)
@@ -79,7 +79,7 @@ namespace Newtonsoft.Json.Utilities
public static void ArgumentNotNullOrEmpty(ICollection collection, string parameterName)
{
ArgumentNotNullOrEmpty(collection, parameterName, string.Format("Collection '{0}' cannot be empty.", parameterName));
ArgumentNotNullOrEmpty(collection, parameterName, "Collection '{0}' cannot be empty.".FormatWith(parameterName));
}
public static void ArgumentNotNullOrEmpty(ICollection collection, string parameterName, string message)