Json.NET 2.0 Beta

New feature - LINQ to JSON!
New feature - Ability to specify how JsonSerializer handles null values when serializing/deserializing.
New feature - Ability to specify how JsonSerializer handles missing values when deserializing.
Change - Improved support for reading and writing JavaScript constructors.
Change - A new JsonWriter can now write additional tokens without erroring.
Bug fix - JsonSerializer handles deserializing dictionaries where the key isn't a string.
Bug fix - JsonReader now correctly parses hex character codes.
This commit is contained in:
JamesNK
2008-02-10 10:56:19 +00:00
parent 487dc81251
commit c1ce4c366f
30 changed files with 2626 additions and 152 deletions
@@ -415,9 +415,6 @@ namespace Newtonsoft.Json.Converters
DeserializeValue(reader, document, manager, propertyName, currentNode);
}
break;
//case JsonToken.String:
// DeserializeValue(reader, document, manager, TextName, currentNode);
// break;
case JsonToken.EndObject:
case JsonToken.EndArray:
return;
+103 -47
View File
@@ -48,8 +48,8 @@ namespace Newtonsoft.Json
Array,
Closed,
PostValue,
ConstructorStart,
Constructor,
ConstructorEnd,
Error,
Finished
}
@@ -142,15 +142,16 @@ namespace Newtonsoft.Json
private void ParseString(char quote)
{
bool stringTerminated = false;
bool hexNumber = false;
int hexCount = 0;
while (!stringTerminated && MoveNext())
{
if (hexNumber)
hexCount++;
switch (_currentChar)
{
//case 0:
//case 0x0A:
//case 0x0D:
// throw new JsonReaderException("Unterminated string");
case '\\':
if (MoveNext())
{
@@ -172,10 +173,8 @@ namespace Newtonsoft.Json
_buffer.Append('\r');
break;
case 'u':
//_buffer.Append((char) Integer.parseInt(next(4), 16));
break;
case 'x':
//_buffer.Append((char) Integer.parseInt(next(2), 16));
// note the start of a hex character
hexNumber = true;
break;
default:
_buffer.Append(_currentChar);
@@ -198,6 +197,19 @@ namespace Newtonsoft.Json
_buffer.Append(_currentChar);
break;
}
if (hexCount == 4)
{
// remove hex characters from buffer, convert to char and then add
string hexString = _buffer.ToString(_buffer.Position - 4, 4);
char hexChar = Convert.ToChar(int.Parse(hexString, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo));
_buffer.Position = _buffer.Position - 4;
_buffer.Append(hexChar);
hexNumber = false;
hexCount = 0;
}
}
if (!stringTerminated)
@@ -273,6 +285,8 @@ namespace Newtonsoft.Json
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValue();
case State.Complete:
break;
@@ -309,6 +323,10 @@ namespace Newtonsoft.Json
SetToken(JsonToken.EndArray);
ClearCurrentChar();
return true;
case ')':
SetToken(JsonToken.EndConstructor);
ClearCurrentChar();
return true;
case '/':
ParseComment();
return true;
@@ -458,6 +476,11 @@ namespace Newtonsoft.Json
Push(JsonType.Array);
ClearCurrentChar();
break;
case JsonToken.StartConstructor:
_currentState = State.ConstructorStart;
Push(JsonType.Constructor);
ClearCurrentChar();
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
ClearCurrentChar();
@@ -468,6 +491,11 @@ namespace Newtonsoft.Json
ClearCurrentChar();
_currentState = State.PostValue;
break;
case JsonToken.EndConstructor:
ValidateEnd(JsonToken.EndConstructor);
ClearCurrentChar();
_currentState = State.PostValue;
break;
case JsonToken.PropertyName:
_currentState = State.Property;
ClearCurrentChar();
@@ -477,7 +505,6 @@ namespace Newtonsoft.Json
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Constructor:
case JsonToken.Date:
_currentState = State.PostValue;
break;
@@ -551,15 +578,17 @@ namespace Newtonsoft.Json
//ClearCurrentChar();
return true;
case ')':
if (_currentState == State.Constructor)
{
_currentState = State.ConstructorEnd;
return false;
}
else
{
throw new JsonReaderException("Unexpected character encountered while parsing value: " + _currentChar);
}
SetToken(JsonToken.EndConstructor);
return true;
//if (_currentState == State.Constructor)
//{
// _currentState = State.ConstructorEnd;
// return false;
//}
//else
//{
// throw new JsonReaderException("Unexpected character encountered while parsing value: " + _currentChar);
//}
default:
if (char.IsWhiteSpace(_currentChar))
{
@@ -605,44 +634,69 @@ namespace Newtonsoft.Json
MoveNext();
}
string constructorName = _buffer.ToString();
_buffer.Position = 0;
List<object> parameters = new List<object>();
EatWhitespace(false);
if (_currentChar == '(' && MoveNext())
{
_currentState = State.Constructor;
if (_currentChar != '(')
throw new JsonReaderException("Unexpected character while parsing constructor: " + _currentChar);
while (ParseValue())
string constructorName = _buffer.ToString();
_buffer.Position = 0;
SetToken(JsonToken.StartConstructor);
_value = constructorName;
_valueType = typeof(string);
if (string.CompareOrdinal(constructorName, "Date") == 0)
{
IList<object> parameters = new List<object>();
MoveNext();
while (ParseValue() && _token != JsonToken.EndConstructor)
{
parameters.Add(_value);
_currentState = State.Constructor;
}
if (string.CompareOrdinal(constructorName, "Date") == 0)
{
long javaScriptTicks = Convert.ToInt64(parameters[0]);
long javaScriptTicks = Convert.ToInt64(parameters[0]);
DateTime date = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
DateTime date = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
SetToken(JsonToken.Date, date);
}
else
{
JavaScriptConstructor constructor = new JavaScriptConstructor(constructorName, new JavaScriptParameters(parameters));
if (_currentState == State.ConstructorEnd)
{
SetToken(JsonToken.Constructor, constructor);
}
}
// move past ')'
MoveNext();
SetToken(JsonToken.Date, date);
}
//{
// _currentState = State.Constructor;
// while (ParseValue())
// {
// parameters.Add(_value);
// _currentState = State.Constructor;
// }
// if (string.CompareOrdinal(constructorName, "Date") == 0)
// {
// long javaScriptTicks = Convert.ToInt64(parameters[0]);
// DateTime date = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
// SetToken(JsonToken.Date, date);
// }
// else
// {
// JavaScriptConstructor constructor = new JavaScriptConstructor(constructorName, new JavaScriptParameters(parameters));
// if (_currentState == State.ConstructorEnd)
// {
// SetToken(JsonToken.Constructor, constructor);
// }
// }
// // move past ')'
// MoveNext();
//}
}
}
}
@@ -716,6 +770,8 @@ namespace Newtonsoft.Json
return JsonType.Object;
case JsonToken.EndArray:
return JsonType.Array;
case JsonToken.EndConstructor:
return JsonType.Constructor;
default:
throw new JsonReaderException("Not a valid close JsonToken: " + token);
}
@@ -803,7 +859,7 @@ namespace Newtonsoft.Json
// check next character to see if start of a comment
return (HasNext() && PeekNext() == '*');
case ')':
if (_currentState == State.Constructor)
if (_currentState == State.Constructor || _currentState == State.ConstructorStart)
return true;
break;
default:
+76 -28
View File
@@ -35,25 +35,6 @@ using System.Globalization;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies reference loop handling options for the <see cref="JsonWriter"/>.
/// </summary>
public enum ReferenceLoopHandling
{
/// <summary>
/// Throw a <see cref="JsonSerializationException"/> when a loop is encountered.
/// </summary>
Error = 0,
/// <summary>
/// Ignore loop references and do not serialize.
/// </summary>
Ignore = 1,
/// <summary>
/// Serialize loop references.
/// </summary>
Serialize = 2
}
/// <summary>
/// Serializes and deserializes objects into and from the Json format.
/// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into Json.
@@ -61,6 +42,8 @@ namespace Newtonsoft.Json
public class JsonSerializer
{
private ReferenceLoopHandling _referenceLoopHandling;
private MissingMemberHandling _missingMemberHandling;
private NullValueHandling _nullValueHandling;
private int _level;
private JsonConverterCollection _converters;
private Dictionary<Type, MemberMappingCollection> _typeMemberMappings;
@@ -74,13 +57,42 @@ namespace Newtonsoft.Json
set
{
if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
{
throw new ArgumentOutOfRangeException("value");
}
_referenceLoopHandling = value;
}
}
/// <summary>
/// Get or set how missing members are handled during deserialization.
/// </summary>
public MissingMemberHandling MissingMemberHandling
{
get { return _missingMemberHandling; }
set
{
if (value < MissingMemberHandling.Error || value > MissingMemberHandling.Ignore)
throw new ArgumentOutOfRangeException("value");
_missingMemberHandling = value;
}
}
/// <summary>
/// Get or set how null values are handled.
/// </summary>
public NullValueHandling NullValueHandling
{
get { return _nullValueHandling; }
set
{
if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
throw new ArgumentOutOfRangeException("value");
_nullValueHandling = value;
}
}
public JsonConverterCollection Converters
{
get
@@ -98,6 +110,7 @@ namespace Newtonsoft.Json
public JsonSerializer()
{
_referenceLoopHandling = ReferenceLoopHandling.Error;
_missingMemberHandling = MissingMemberHandling.Error;
}
#region Deserialize
@@ -216,15 +229,22 @@ namespace Newtonsoft.Json
case JsonToken.Date:
value = EnsureType(reader.Value, objectType);
break;
case JsonToken.Constructor:
value = reader.Value.ToString();
case JsonToken.StartConstructor:
case JsonToken.EndConstructor:
string constructorName = reader.Value.ToString();
//if (string.CompareOrdinal(constructorName, "Date") == 0)
// value = CreateDate(reader);
//else
//TODO: use objectType plus constructor arguments to instantiate object
value = constructorName;
break;
case JsonToken.Null:
case JsonToken.Undefined:
value = null;
break;
default:
throw new JsonSerializationException("Unexpected token whil deserializing object: " + reader.TokenType);
throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType);
}
}
@@ -233,6 +253,25 @@ namespace Newtonsoft.Json
return value;
}
private DateTime CreateDate(JsonReader reader)
{
// move to parameter
if (!reader.Read())
throw new JsonSerializationException("Unexpected end while creating date.");
//TODO: add support for Date constructor with multiple arguments
long ticks = Convert.ToInt64(reader.Value);
DateTime date = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(ticks);
// move to constructor end
if (!reader.Read())
throw new JsonSerializationException("Unexpected end while creating date.");
if (reader.TokenType != JsonToken.EndConstructor)
throw new JsonSerializationException("Unexpected token while creating date: " + reader.TokenType);
return date;
}
private object EnsureType(object value, Type targetType)
{
// do something about null value when the targetType is a valuetype?
@@ -342,20 +381,26 @@ namespace Newtonsoft.Json
value = GetObject(reader, memberType);
if (_nullValueHandling == NullValueHandling.Ignore && value == null)
return;
ReflectionUtils.SetMemberValue(memberMapping.Member, target, value);
}
else if (typeof(IDictionary).IsAssignableFrom(targetType))
{
// attempt to get the IDictionary's type
memberType = ReflectionUtils.GetDictionaryValueType(target.GetType());
memberType = ReflectionUtils.GetDictionaryValueType(targetType);
value = GetObject(reader, memberType);
((IDictionary)target).Add(memberName, value);
Type keyType = ReflectionUtils.GetDictionaryKeyType(targetType);
object keyValue = EnsureType(memberName, keyType);
((IDictionary)target).Add(keyValue, value);
}
else
{
throw new JsonSerializationException(string.Format("Could not find member '{0}' on object of type '{1}'", memberName, targetType.GetType().Name));
if (_missingMemberHandling == MissingMemberHandling.Error)
throw new JsonSerializationException(string.Format("Could not find member '{0}' on object of type '{1}'", memberName, targetType.GetType().Name));
}
}
@@ -557,6 +602,9 @@ namespace Newtonsoft.Json
{
object memberValue = ReflectionUtils.GetMemberValue(member, value);
if (_nullValueHandling == NullValueHandling.Ignore && memberValue == null)
return;
if (writer.SerializeStack.IndexOf(memberValue) != -1)
{
switch (_referenceLoopHandling)
+6 -2
View File
@@ -49,6 +49,10 @@ namespace Newtonsoft.Json
/// <summary>
/// An object property name.
/// </summary>
StartConstructor,
/// <summary>
/// A constructor end token.
/// </summary>
PropertyName,
/// <summary>
/// A comment.
@@ -87,9 +91,9 @@ namespace Newtonsoft.Json
/// </summary>
EndArray,
/// <summary>
/// A JavaScript object constructor.
/// A constructor start token.
/// </summary>
Constructor,
EndConstructor,
/// <summary>
/// A Date.
/// </summary>
+49 -13
View File
@@ -36,6 +36,7 @@ namespace Newtonsoft.Json
{
Object,
Array,
Constructor,
None
}
@@ -63,6 +64,10 @@ namespace Newtonsoft.Json
/// </summary>
Array,
/// <summary>
/// A constructor is being written.
/// </summary>
Constructor,
/// <summary>
/// A property is being written.
/// </summary>
Property,
@@ -100,20 +105,23 @@ namespace Newtonsoft.Json
Object,
ArrayStart,
Array,
ConstructorStart,
Constructor,
Closed,
Error
}
// array that gives a new state based on the current state an the token being written
private static readonly State[,] stateArray = {
// Start PropertyName ObjectStart Object ArrayStart Array Closed Error
//
/* None */{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartProperty */{ State.Error, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error },
/* Comment */{ State.Error, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Error, State.Error },
/* Value */{ State.Error, State.Object, State.Error, State.Error, State.Array, State.Array, State.Error, State.Error },
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */{ State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* StartProperty */{ State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value */{ State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
};
private int _top;
@@ -157,6 +165,9 @@ namespace Newtonsoft.Json
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
@@ -322,6 +333,20 @@ namespace Newtonsoft.Json
AutoCompleteClose(JsonToken.EndArray);
}
public void WriteStartConstructor(string name)
{
AutoComplete(JsonToken.StartConstructor);
Push(JsonType.Constructor);
_writer.Write("new ");
_writer.Write(name);
_writer.Write("(");
}
public void WriteEndConstructor()
{
AutoCompleteClose(JsonToken.EndConstructor);
}
/// <summary>
/// Writes the property name of a name/value pair on a Json object.
/// </summary>
@@ -360,6 +385,9 @@ namespace Newtonsoft.Json
case JsonType.Array:
WriteEndArray();
break;
case JsonType.Constructor:
WriteEndConstructor();
break;
default:
throw new JsonWriterException("Unexpected type when writing end: " + type);
}
@@ -381,6 +409,8 @@ namespace Newtonsoft.Json
return JsonType.Object;
case JsonToken.EndArray:
return JsonType.Array;
case JsonToken.EndConstructor:
return JsonType.Constructor;
default:
throw new JsonWriterException("No type for token: " + token);
}
@@ -394,6 +424,8 @@ namespace Newtonsoft.Json
return JsonToken.EndObject;
case JsonType.Array:
return JsonToken.EndArray;
case JsonType.Constructor:
return JsonToken.EndConstructor;
default:
throw new JsonWriterException("No close token for type: " + type);
}
@@ -434,6 +466,9 @@ namespace Newtonsoft.Json
case JsonToken.EndArray:
_writer.Write("]");
break;
case JsonToken.EndConstructor:
_writer.Write(")");
break;
default:
throw new JsonWriterException("Invalid JsonToken: " + token);
}
@@ -491,7 +526,7 @@ namespace Newtonsoft.Json
case JsonToken.Undefined:
case JsonToken.Date:
// a value is being written
token = 5;
token = 6;
break;
}
@@ -501,7 +536,7 @@ namespace Newtonsoft.Json
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()));
if ((_currentState == State.Object || _currentState == State.Array) && tokenBeingWritten != JsonToken.Comment)
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
_writer.Write(',');
}
@@ -511,8 +546,9 @@ namespace Newtonsoft.Json
_writer.Write(' ');
}
if (tokenBeingWritten == JsonToken.PropertyName ||
(WriteState == WriteState.Array))
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((tokenBeingWritten == JsonToken.PropertyName && WriteState != WriteState.Start) ||
WriteState == WriteState.Array || WriteState == WriteState.Constructor)
{
WriteIndent();
}
@@ -729,4 +765,4 @@ namespace Newtonsoft.Json
Close();
}
}
}
}
+143
View File
@@ -0,0 +1,143 @@
#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.Utilities;
using System.Collections;
namespace Newtonsoft.Json.Linq
{
public static class Extensions
{
public static IEnumerable<JToken> Ancestors<T>(this IEnumerable<T> source) where T : JToken
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(j => j.Ancestors());
}
//TODO
//public static IEnumerable<JObject> AncestorsAndSelf<T>(this IEnumerable<T> source) where T : JObject
//{
// ValidationUtils.ArgumentNotNull(source, "source");
// return source.SelectMany(j => j.AncestorsAndSelf());
//}
public static IEnumerable<JToken> Descendants<T>(this IEnumerable<T> source) where T : JContainer
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(j => j.Descendants());
}
//TODO
//public static IEnumerable<JObject> DescendantsAndSelf<T>(this IEnumerable<T> source) where T : JContainer
//{
// ValidationUtils.ArgumentNotNull(source, "source");
// return source.SelectMany(j => j.DescendantsAndSelf());
//}
public static IEnumerable<JProperty> Properties(this IEnumerable<JObject> source)
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(d => d.Properties());
}
public static IEnumerable<T> PropertyValues<T>(this IEnumerable<JObject> source, string name)
{
ValidationUtils.ArgumentNotNull(source, "source");
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 : JContainer
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(c => c.Children());
}
public static IEnumerable<U> Children<U>(this IEnumerable<JArray> source)
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(c => c.Children()).Convert<JToken, U>();
}
internal static IEnumerable<U> Convert<T, U>(this IEnumerable<T> source) where T : JToken
{
ValidationUtils.ArgumentNotNull(source, "source");
bool cast = typeof(JToken).IsAssignableFrom(typeof(U));
foreach (JToken token in source)
{
yield return Convert<JToken, U>(token, cast);
}
}
internal static U Convert<T, U>(this T token) where T : JToken
{
bool cast = typeof(JToken).IsAssignableFrom(typeof(U));
return Convert<T, U>(token, cast);
}
internal static U Convert<T, U>(this T token, bool cast) where T : JToken
{
if (cast)
{
// HACK
return (U)(object)token;
}
else
{
JValue value = token as JValue;
if (value == null)
throw new InvalidCastException(string.Format("Cannot cast {0} to {1}.", token.GetType(), typeof(T)));
return (U)System.Convert.ChangeType(value.Value, typeof(U));
}
}
//TODO
//public static void Remove<T>(this IEnumerable<T> source) where T : JContainer;
}
}
+106
View File
@@ -0,0 +1,106 @@
#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.Utilities;
using System.IO;
namespace Newtonsoft.Json.Linq
{
public class JArray : JContainer
{
public override JsonTokenType Type
{
get { return JsonTokenType.Array; }
}
public JArray(params object[] content) : this((object)content)
{
}
public JArray(object content)
{
Add(content);
}
public int Count()
{
return Children().Count();
}
public static JArray Load(JsonReader reader)
{
if (reader.TokenType == JsonToken.None)
{
if (!reader.Read())
throw new Exception("Error reading JArray from JsonReader.");
}
if (reader.TokenType != JsonToken.StartArray)
{
throw new Exception("Current JsonReader item is not an object.");
}
else
{
if (!reader.Read())
throw new Exception("Error reading JArray from JsonReader.");
}
JArray a = new JArray();
a.ReadContentFrom(reader);
return a;
}
public static JArray Parse(string json)
{
JsonReader jsonReader = new JsonReader(new StringReader(json));
return Load(jsonReader);
}
internal override void ValidateObject(JToken o, JToken previous)
{
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));
}
public override void WriteTo(JsonWriter writer)
{
writer.WriteStartArray();
foreach (JToken token in Children())
{
token.WriteTo(writer);
}
writer.WriteEndArray();
}
}
}
+92
View File
@@ -0,0 +1,92 @@
#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.Utilities;
namespace Newtonsoft.Json.Linq
{
public class JConstructor : JContainer
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public override JsonTokenType Type
{
get { return JsonTokenType.Constructor; }
}
public JConstructor()
{
}
public JConstructor(string name, params object[] content)
: this(name, (object)content)
{
}
public JConstructor(string name, object content)
: this(name)
{
Add(content);
}
public JConstructor(string name)
{
_name = name;
}
internal override void ValidateObject(JToken o, JToken previous)
{
ValidationUtils.ArgumentNotNull(o, "o");
switch (o.Type)
{
case JsonTokenType.Property:
throw new ArgumentException(string.Format("An item of type {0} cannot be added to content.", o.Type));
}
}
public override void WriteTo(JsonWriter writer)
{
writer.WriteStartConstructor(_name);
foreach (JToken token in Children())
{
token.WriteTo(writer);
}
writer.WriteEndConstructor();
}
}
}
+290
View File
@@ -0,0 +1,290 @@
#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.Utilities;
using System.Collections;
namespace Newtonsoft.Json.Linq
{
public abstract class JContainer : JToken
{
private JToken _content;
internal JToken Content
{
get { return _content; }
set { _content = value; }
}
public JToken First
{
get
{
if (Last == null)
return null;
return Last.Next;
}
}
public JToken Last
{
get { return _content; }
}
public IEnumerable<JToken> Children()
{
JToken first = First;
JToken current = first;
if (current == null)
yield break;
do
{
yield return current;
} while ((current = current.Next) != first);
}
public IEnumerable<T> Children<T>()
{
return Children().Convert<JToken, T>();
}
public IEnumerable<JToken> Descendants()
{
foreach (JToken o in Children())
{
yield return o;
JContainer c = o as JContainer;
if (c != null)
{
foreach (JToken d in c.Descendants())
{
yield return d;
}
}
}
}
public virtual void Add(object content)
{
if (content is IEnumerable && !(content is string))
{
IEnumerable enumerable = content as IEnumerable;
foreach (object c in enumerable)
{
Add(c);
}
}
else
{
JToken o = CreateFromContent(content);
JToken last = Last;
JToken next = First ?? o;
o.Parent = this;
o.Next = next;
if (last != null)
last.Next = o;
_content = o;
}
}
public void AddFirst(object content)
{
JToken o = CreateFromContent(content);
JToken last = Parent.Last;
o.Parent = Parent;
o.Next = last.Next;
last.Next = o;
}
protected JToken CreateFromContent(object content)
{
if (content is JToken)
return (JToken)content;
return new JValue(content);
}
public JsonWriter CreateWriter()
{
return null;
}
public void ReplaceAll(object content)
{
RemoveAll();
Add(content);
}
public void RemoveAll()
{
while (_content != null)
{
JToken o = _content;
JToken next = o.Next;
if (o != _content || next != o.Next)
throw new InvalidOperationException("This operation was corrupted by external code.");
if (next != o)
o.Next = next.Next;
else
_content = null;
next.Parent = null;
next.Next = null;
}
}
internal void Remove(JToken o)
{
if (o.Parent != this)
throw new InvalidOperationException("This operation was corrupted by external code.");
JToken content = _content;
while (_content.Next != o)
{
content = content.Next;
}
if (content == o)
{
_content = null;
}
else
{
if (_content == o)
{
_content = content;
}
content.Next = o.Next;
}
o.Parent = null;
o.Next = null;
}
internal abstract void ValidateObject(JToken o, JToken previous);
internal void AddObjectSkipNotify(JToken o)
{
ValidateObject(o, this);
Add(o);
}
internal void ReadContentFrom(JsonReader r)
{
ValidationUtils.ArgumentNotNull(r, "r");
JContainer parent = this;
do
{
if (parent is JProperty)
{
if (((JProperty)parent).Value != null)
parent = parent.Parent;
}
switch (r.TokenType)
{
case JsonToken.None:
// new reader. move to actual content
break;
case JsonToken.StartArray:
JArray a = new JArray();
parent.AddObjectSkipNotify(a);
parent = a;
break;
case JsonToken.EndArray:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.StartObject:
JObject o = new JObject();
parent.AddObjectSkipNotify(o);
parent = o;
break;
case JsonToken.EndObject:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.StartConstructor:
JConstructor constructor = new JConstructor();
constructor.Name = r.Value.ToString();
parent.AddObjectSkipNotify(constructor);
parent = constructor;
break;
case JsonToken.EndConstructor:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.String:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Date:
case JsonToken.Boolean:
parent.AddObjectSkipNotify(new JValue(r.Value));
break;
case JsonToken.Comment:
parent.AddObjectSkipNotify(JValue.CreateComment(r.Value.ToString()));
break;
case JsonToken.Null:
parent.AddObjectSkipNotify(JValue.Null);
break;
case JsonToken.Undefined:
parent.AddObjectSkipNotify(JValue.Undefined);
break;
case JsonToken.PropertyName:
JProperty property = new JProperty(r.Value.ToString());
parent.AddObjectSkipNotify(property);
parent = property;
break;
default:
throw new InvalidOperationException(string.Format("The JsonReader should not be on a token of type {0}.", r.TokenType));
}
}
while (r.Read());
}
}
}
+133
View File
@@ -0,0 +1,133 @@
#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 System.IO;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Linq
{
public class JObject : JContainer
{
public JObject()
{
}
public JObject(params object[] content) : this((object)content)
{
}
public JObject(object content)
{
Add(content);
}
public override JsonTokenType Type
{
get { return JsonTokenType.Object; }
}
public IEnumerable<JProperty> Properties()
{
return Children().Cast<JProperty>();
}
public JProperty Property(string name)
{
return Properties()
.Where(p => string.Compare(p.Name, name, StringComparison.Ordinal) == 0)
.SingleOrDefault();
}
public IEnumerable<JToken> PropertyValues()
{
return Properties().Select(p => p.Value);
}
public T PropertyValue<T>(string name)
{
JProperty property = Property(name);
if (property == null)
throw new Exception(string.Format("Property '{0}' does not exist in JSON object.", name));
// HACK
return Extensions.Convert<JToken, T>(property.Value);
}
public static JObject Load(JsonReader reader)
{
if (reader.TokenType == JsonToken.None)
{
if (!reader.Read())
throw new Exception("Error reading JObject from JsonReader.");
}
if (reader.TokenType != JsonToken.StartObject)
{
throw new Exception("Current JsonReader item is not an object.");
}
else
{
if (!reader.Read())
throw new Exception("Error reading JObject from JsonReader.");
}
JObject o = new JObject();
o.ReadContentFrom(reader);
return o;
}
public static JObject Parse(string json)
{
JsonReader jsonReader = new JsonReader(new StringReader(json));
return Load(jsonReader);
}
internal override void ValidateObject(JToken o, JToken previous)
{
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));
}
public override void WriteTo(JsonWriter writer)
{
writer.WriteStartObject();
foreach (JProperty property in Properties())
{
property.WriteTo(writer);
}
writer.WriteEndObject();
}
}
}
+86
View File
@@ -0,0 +1,86 @@
#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.Utilities;
namespace Newtonsoft.Json.Linq
{
public class JProperty : JContainer
{
private readonly string _name;
public string Name
{
get { return _name; }
}
public JToken Value
{
get { return Last; }
set
{
ReplaceAll(value);
}
}
public override JsonTokenType Type
{
get { return JsonTokenType.Property; }
}
public JProperty(string name)
{
ValidationUtils.ArgumentNotNullOrEmpty(name, "name");
_name = name;
}
public JProperty(string name, object value)
{
ValidationUtils.ArgumentNotNullOrEmpty(name, "name");
_name = name;
Value = CreateFromContent(value);
}
internal override void ValidateObject(JToken o, JToken previous)
{
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));
}
public override void WriteTo(JsonWriter writer)
{
writer.WritePropertyName(_name);
Value.WriteTo(writer);
}
}
}
+415
View File
@@ -0,0 +1,415 @@
#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 System.IO;
namespace Newtonsoft.Json.Linq
{
public abstract class JToken
{
private JContainer _parent;
private JToken _next;
public JContainer Parent
{
get { return _parent; }
internal set { _parent = value; }
}
public JToken Root
{
get { return null; }
}
public abstract JsonTokenType Type { get; }
public JToken Next
{
get
{
if (_parent == null)
return null;
return _next;
}
internal set { _next = value; }
}
public JToken Previous
{
get
{
if (_parent == null)
return null;
JToken parentNext = ((JToken) _parent.Content).Next;
JToken parentNextBefore = null;
while (parentNext != this)
{
parentNextBefore = parentNext;
parentNext = parentNext.Next;
}
return parentNextBefore;
}
}
public bool HasValues
{
get { return false; }
}
public IEnumerable<JToken> Ancestors()
{
for (JToken parent = Parent; parent != null; parent = parent.Parent)
{
yield return parent;
}
}
public IEnumerable<JToken> AfterSelf()
{
if (Parent == null)
yield break;
for (JToken o = Next; o != null; o = o.Next)
yield return o;
}
public IEnumerable<JToken> BeforeSelf()
{
for (JToken o = Parent.First; o != this; o = o.Next)
yield return o;
}
//public IEnumerable<JObject> ObjectsAfterSelf()
//{
// return null;
//}
//public IEnumerable<JObject> ObjectsBeforeSelf()
//{
// return null;
//}
public void Remove()
{
if (_parent == null)
throw new InvalidOperationException("The parent is missing.");
_parent.Remove(this);
}
public void Replace(JToken value)
{
}
public abstract void WriteTo(JsonWriter writer);
public override string ToString()
{
using (StringWriter sw = new StringWriter())
{
JsonWriter jw = new JsonWriter(sw);
jw.Formatting = Formatting.Indented;
WriteTo(jw);
return sw.ToString();
}
}
private static JValue EnsureValue(JToken value)
{
if (value == null)
throw new ArgumentNullException("value");
if (value is JProperty)
value = ((JProperty)value).Value;
JValue v = value as JValue;
return v;
}
private static bool IsNullable(JToken o)
{
return (o.Type == JsonTokenType.Undefined || o.Type == JsonTokenType.Null);
}
private static bool ValidateFloat(JToken o, bool nullable)
{
return (o.Type == JsonTokenType.Float || o.Type == JsonTokenType.Integer || (nullable && IsNullable(o)));
}
private static bool ValidateInteger(JToken o, bool nullable)
{
return (o.Type == JsonTokenType.Integer || (nullable && IsNullable(o)));
}
private static bool ValidateDate(JToken o, bool nullable)
{
return (o.Type == JsonTokenType.Date || (nullable && IsNullable(o)));
}
private static bool ValidateBoolean(JToken o, bool nullable)
{
return (o.Type == JsonTokenType.Boolean || (nullable && IsNullable(o)));
}
private static bool ValidateString(JToken o)
{
return (o.Type == JsonTokenType.String || IsNullable(o));
}
#region Cast operators
public static explicit operator bool(JToken value)
{
JValue v = EnsureValue(value);
if (v == null || !ValidateBoolean(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Boolean.", v.Type));
return (bool)v.Value;
}
public static explicit operator DateTimeOffset(JToken value)
{
JValue v = EnsureValue(value);
if (v == null || !ValidateDate(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to DateTimeOffset.", v.Type));
return (DateTimeOffset)v.Value;
}
public static explicit operator bool?(JToken value)
{
if (value == null)
return null;
JValue v = EnsureValue(value);
if (v == null || !ValidateBoolean(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to Boolean.", v.Type));
return (bool?)v.Value;
}
public static explicit operator long(JToken value)
{
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Int64.", v.Type));
return (long)v.Value;
}
public static explicit operator DateTime?(JToken value)
{
if (value == null)
return null;
JValue v = EnsureValue(value);
if (v == null || !ValidateDate(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to DateTime.", v.Type));
return (DateTime?)v.Value;
}
public static explicit operator DateTimeOffset?(JToken value)
{
if (value == null)
return null;
JValue v = EnsureValue(value);
if (v == null || !ValidateDate(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to DateTimeOffset.", v.Type));
return (DateTimeOffset?)v.Value;
}
public static explicit operator decimal?(JToken value)
{
if (value == null)
return null;
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to Decimal.", v.Type));
return (decimal?)v.Value;
}
public static explicit operator double?(JToken value)
{
if (value == null)
return null;
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to Double.", v.Type));
return (double?)v.Value;
}
public static explicit operator int(JToken value)
{
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Int32.", v.Type));
return Convert.ToInt32(v.Value);
}
public static explicit operator int?(JToken value)
{
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 Int32.", v.Type));
return (v.Value != null) ? (int?)Convert.ToInt32(v.Value) : 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));
return (DateTime)v.Value;
}
public static explicit operator long?(JToken value)
{
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));
return (long?)v.Value;
}
public static explicit operator float?(JToken value)
{
if (value == null)
return null;
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, true))
throw new ArgumentException(string.Format("Can not convert {0} to Single.", v.Type));
return (float?)v.Value;
}
public static explicit operator decimal(JToken value)
{
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Decimal.", v.Type));
return (decimal)v.Value;
}
public static explicit operator uint?(JToken value)
{
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 UInt32.", v.Type));
return (uint?)v.Value;
}
public static explicit operator ulong?(JToken value)
{
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 UInt64.", v.Type));
return (ulong?)v.Value;
}
public static explicit operator double(JToken value)
{
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Double.", v.Type));
return (double)v.Value;
}
public static explicit operator float(JToken value)
{
JValue v = EnsureValue(value);
if (v == null || !ValidateFloat(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to Single.", v.Type));
return (float)v.Value;
}
public static explicit operator string(JToken value)
{
if (value == null)
return null;
JValue v = EnsureValue(value);
if (v == null || !ValidateString(v))
throw new ArgumentException(string.Format("Can not convert {0} to String.", v.Type));
return (string)v.Value;
}
public static explicit operator uint(JToken value)
{
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to UInt32.", v.Type));
return (uint)v.Value;
}
public static explicit operator ulong(JToken value)
{
JValue v = EnsureValue(value);
if (v == null || !ValidateInteger(v, false))
throw new ArgumentException(string.Format("Can not convert {0} to UInt64.", v.Type));
return (ulong)v.Value;
}
#endregion
}
}
+149
View File
@@ -0,0 +1,149 @@
#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;
namespace Newtonsoft.Json.Linq
{
public class JValue : JToken
{
private JsonTokenType _valueType;
private object _value;
public static readonly JValue Null = new JValue(null, JsonTokenType.Null);
public static readonly JValue Undefined = new JValue(null, JsonTokenType.Undefined);
private JValue(object value, JsonTokenType type)
{
_value = value;
_valueType = type;
}
public JValue(long value)
: this(value, JsonTokenType.Integer)
{
}
public JValue(double value)
: this(value, JsonTokenType.Float)
{
}
public JValue(DateTime value)
: this(value, JsonTokenType.Date)
{
}
public JValue(bool value)
: this(value, JsonTokenType.Boolean)
{
}
public JValue(string value)
: this(value, JsonTokenType.String)
{
}
public JValue(object value) : this(value, GetValueType(value))
{
}
public static JValue CreateComment(string value)
{
return new JValue(value, JsonTokenType.Comment);
}
private static JsonTokenType GetValueType(object value)
{
if (value == null)
return JsonTokenType.Null;
else if (value is string)
return JsonTokenType.String;
else if (value is long || value is int || value is short
|| value is ulong || value is uint || value is ushort)
return JsonTokenType.Integer;
else if (value is double || value is float)
return JsonTokenType.Float;
else if (value is DateTime)
return JsonTokenType.Date;
else if (value is bool)
return JsonTokenType.Boolean;
throw new ArgumentException(string.Format("Could not determin JSON object type for type {0}.", value.GetType()));
}
public override JsonTokenType Type
{
get { return _valueType; }
}
public object Value
{
get { return _value; }
set { _value = value; }
}
public static JToken CreateString(string value)
{
return new JValue(value, JsonTokenType.String);
}
public override void WriteTo(JsonWriter writer)
{
switch (_valueType)
{
case JsonTokenType.Comment:
writer.WriteComment(_value.ToString());
break;
case JsonTokenType.Integer:
writer.WriteValue(Convert.ToInt64(_value));
break;
case JsonTokenType.Float:
writer.WriteValue(Convert.ToDouble(_value));
break;
case JsonTokenType.String:
writer.WriteValue(_value.ToString());
break;
case JsonTokenType.Boolean:
writer.WriteValue(Convert.ToBoolean(_value));
break;
case JsonTokenType.Null:
writer.WriteNull();
break;
case JsonTokenType.Undefined:
writer.WriteUndefined();
break;
case JsonTokenType.Date:
writer.WriteValue(Convert.ToDateTime(_value));
break;
default:
throw new ArgumentOutOfRangeException("TokenType", _valueType, "Unexpected token type.");
}
}
}
}
+48
View File
@@ -0,0 +1,48 @@
#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;
namespace Newtonsoft.Json.Linq
{
public enum JsonTokenType
{
Object,
Array,
Constructor,
Property,
Comment,
Integer,
Float,
String,
Boolean,
Null,
Undefined,
Date
}
}
+25
View File
@@ -1,3 +1,28 @@
#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.Text;
@@ -1,3 +1,28 @@
#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.Text;
@@ -0,0 +1,43 @@
#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.Text;
namespace Newtonsoft.Json
{
public enum MissingMemberHandling
{
/// <summary>
/// Throw a <see cref="JsonSerializationException"/> when a missing member is encountered during deserialization.
/// </summary>
Error = 0,
/// <summary>
/// Ignore a missing member and do not attempt to deserialize it.
/// </summary>
Ignore = 1
}
}
+57 -3
View File
@@ -1,8 +1,8 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}</ProjectGuid>
<OutputType>Library</OutputType>
@@ -20,6 +20,27 @@
</SccAuxPath>
<SccProvider>
</SccProvider>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>2.0</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -29,7 +50,8 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>bin\Debug\Newtonsoft.Json.XML</DocumentationFile>
<DocumentationFile>
</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -42,6 +64,9 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
@@ -66,8 +91,20 @@
<Compile Include="JavaScriptConvert.cs" />
<Compile Include="JsonSerializationException.cs" />
<Compile Include="JsonSerializer.cs" />
<Compile Include="Linq\Extensions.cs" />
<Compile Include="Linq\JConstructor.cs" />
<Compile Include="Linq\JContainer.cs" />
<Compile Include="Linq\JObject.cs" />
<Compile Include="Linq\JArray.cs" />
<Compile Include="Linq\JToken.cs" />
<Compile Include="Linq\JProperty.cs" />
<Compile Include="Linq\JsonTokenType.cs" />
<Compile Include="Linq\JValue.cs" />
<Compile Include="MemberMapping.cs" />
<Compile Include="MemberMappingCollection.cs" />
<Compile Include="MissingMemberHandling.cs" />
<Compile Include="NullValueHandling.cs" />
<Compile Include="ReferenceLoopHandling.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="JsonToken.cs" />
<Compile Include="JsonWriter.cs" />
@@ -80,5 +117,22 @@
<Compile Include="Utilities\StringUtils.cs" />
<Compile Include="Utilities\ValidationUtils.cs" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Framework.2.0">
<Visible>False</Visible>
<ProductName>.NET Framework 2.0 %28x86%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
<Visible>False</Visible>
<ProductName>.NET Framework 3.0 %28x86%29</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
+47
View File
@@ -0,0 +1,47 @@
#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;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies null value handling options for the <see cref="JsonWriter"/>.
/// </summary>
public enum NullValueHandling
{
/// <summary>
/// Include null values when serializing and deserializing objects.
/// </summary>
Include = 0,
/// <summary>
/// Ignore null values when serializing and deserializing objects.
/// </summary>
Ignore = 1
}
}
@@ -54,5 +54,5 @@ using System.Security;
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
@@ -0,0 +1,50 @@
#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.Text;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies reference loop handling options for the <see cref="JsonWriter"/>.
/// </summary>
public enum ReferenceLoopHandling
{
/// <summary>
/// Throw a <see cref="JsonSerializationException"/> when a loop is encountered.
/// </summary>
Error = 0,
/// <summary>
/// Ignore loop references and do not serialize.
/// </summary>
Ignore = 1,
/// <summary>
/// Serialize loop references.
/// </summary>
Serialize = 2
}
}
+7 -1
View File
@@ -84,7 +84,13 @@ namespace Newtonsoft.Json
public override string ToString()
{
return new string(_buffer, 0, _position);
return ToString(0, _position);
}
public string ToString(int start, int length)
{
// TODO: validation
return new string(_buffer, start, length);
}
}
}
@@ -29,11 +29,19 @@ using System.Collections.ObjectModel;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Linq;
namespace Newtonsoft.Json.Utilities
{
internal static class CollectionUtils
{
public static IEnumerable<T> CastValid<T>(this IEnumerable enumerable)
{
ValidationUtils.ArgumentNotNull(enumerable, "enumerable");
return enumerable.Cast<object>().Where(o => o is T).Cast<T>();
}
public static List<T> CreateList<T>(params T[] values)
{
return new List<T>(values);
@@ -209,28 +209,52 @@ namespace Newtonsoft.Json.Utilities
}
}
public static Type GetDictionaryValueType(Type type)
private static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(dictionaryType, "type");
Type genericDictionaryType;
if (IsSubClass(type, typeof(IDictionary<,>), out genericDictionaryType))
if (IsSubClass(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType))
{
if (genericDictionaryType.IsGenericTypeDefinition)
throw new Exception(string.Format("Type {0} is not a dictionary.", type));
throw new Exception(string.Format("Type {0} is not a dictionary.", dictionaryType));
return genericDictionaryType.GetGenericArguments()[1];
Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments();
keyType = dictionaryGenericArguments[0];
valueType = dictionaryGenericArguments[1];
return;
}
else if (typeof(IDictionary).IsAssignableFrom(type))
else if (typeof(IDictionary).IsAssignableFrom(dictionaryType))
{
return null;
keyType = null;
valueType = null;
return;
}
else
{
throw new Exception(string.Format("Type {0} is not a dictionary.", type));
throw new Exception(string.Format("Type {0} is not a dictionary.", dictionaryType));
}
}
public static Type GetDictionaryValueType(Type dictionaryType)
{
Type keyType;
Type valueType;
GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType);
return valueType;
}
public static Type GetDictionaryKeyType(Type dictionaryType)
{
Type keyType;
Type valueType;
GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType);
return keyType;
}
/// <summary>
/// Tests whether the list's items are their unitialized value.
/// </summary>