📄 jsonreader.cs
字号:
#region BuildTools License
/*---------------------------------------------------------------------------------*\
BuildTools distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2008 Stephen M. McKamey
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 BuildTools License
using System;
using System.ComponentModel;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace JsonFx.Json
{
/// <summary>
/// Reader for consuming JSON data
/// </summary>
public class JsonReader
{
#region Constants
internal const string LiteralFalse = "false";
internal const string LiteralTrue = "true";
internal const string LiteralNull = "null";
internal const string LiteralNotANumber = "NaN";
internal const string LiteralPositiveInfinity = "Infinity";
internal const string LiteralNegativeInfinity = "-Infinity";
internal const char OperatorNegate = '-';
internal const char OperatorUnaryPlus = '+';
internal const char OperatorArrayStart = '[';
internal const char OperatorArrayEnd = ']';
internal const char OperatorObjectStart = '{';
internal const char OperatorObjectEnd = '}';
internal const char OperatorStringDelim = '"';
internal const char OperatorStringDelimAlt = '\'';
internal const char OperatorValueDelim = ',';
internal const char OperatorNameDelim = ':';
internal const char OperatorCharEscape = '\\';
private const string CommentStart = "/*";
private const string CommentEnd = "*/";
private const string CommentLine = "//";
private const string LineEndings = "\r\n";
private const string ErrorUnrecognizedToken = "Illegal JSON sequence.";
private const string ErrorUnterminatedComment = "Unterminated comment block.";
private const string ErrorUnterminatedObject = "Unterminated JSON object.";
private const string ErrorUnterminatedArray = "Unterminated JSON array.";
private const string ErrorUnterminatedString = "Unterminated JSON string.";
private const string ErrorIllegalNumber = "Illegal JSON number.";
private const string ErrorExpectedString = "Expected JSON string.";
private const string ErrorExpectedObject = "Expected JSON object.";
private const string ErrorExpectedArray = "Expected JSON array.";
private const string ErrorExpectedPropertyName = "Expected JSON object property name.";
private const string ErrorExpectedPropertyNameDelim = "Expected JSON object property name delimiter.";
private const string ErrorNullValueType = "{0} does not accept null as a value";
private const string ErrorDefaultCtor = "Only objects with default constructors can be deserialized.";
private const string ErrorGenericIDictionary = "Types which implement Generic IDictionary<TKey, TValue> also need to implement IDictionary to be deserialized.";
#endregion Constants
#region Fields
private Dictionary<Type, Dictionary<string, MemberInfo>> MemberMapCache = null;
private readonly string Source = null;
private readonly int SourceLength = 0;
private int index = 0;
private bool allowNullValueTypes = false;
private string typeHintName = null;
#endregion Fields
#region Init
/// <summary>
/// Ctor.
/// </summary>
/// <param name="input">TextReader containing source</param>
public JsonReader(TextReader input)
{
this.Source = input.ReadToEnd();
this.SourceLength = this.Source.Length;
}
/// <summary>
/// Ctor.
/// </summary>
/// <param name="input">Stream containing source</param>
public JsonReader(Stream input)
{
using (StreamReader reader = new StreamReader(input, true))
{
this.Source = reader.ReadToEnd();
}
this.SourceLength = this.Source.Length;
}
/// <summary>
/// Ctor.
/// </summary>
/// <param name="input">string containing source</param>
public JsonReader(string input)
{
this.Source = input;
this.SourceLength = this.Source.Length;
}
/// <summary>
/// Ctor.
/// </summary>
/// <param name="input">StringBuilder containing source</param>
public JsonReader(StringBuilder input)
{
this.Source = input.ToString();
this.SourceLength = this.Source.Length;
}
#endregion Init
#region Properties
/// <summary>
/// Gets and sets if ValueTypes can accept values of null
/// </summary>
/// <remarks>
/// Only affects deserialization: if a ValueType is assigned the
/// value of null, it will receive the value default(TheType).
/// Setting this to false, throws an exception if null is
/// specified for a ValueType member.
/// </remarks>
public bool AllowNullValueTypes
{
get { return this.allowNullValueTypes; }
set { this.allowNullValueTypes = value; }
}
/// <summary>
/// Gets and sets the property name used for type hinting.
/// </summary>
public string TypeHintName
{
get { return this.typeHintName; }
set { this.typeHintName = value; }
}
#endregion Properties
#region Parsing Methods
/// <summary>
/// Convert from JSON string to Object graph
/// </summary>
/// <returns></returns>
public object Deserialize()
{
return this.Deserialize(null);
}
/// <summary>
/// Convert from JSON string to Object graph of specific Type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public object Deserialize(Type type)
{
// should this run through a preliminary test here?
return this.Read(type, false);
}
private object Read(Type expectedType, bool typeIsHint)
{
if (expectedType == typeof(Object))
{
expectedType = null;
}
JsonToken token = this.Tokenize();
switch (token)
{
case JsonToken.ObjectStart:
{
return this.ReadObject(typeIsHint ? null : expectedType);
}
case JsonToken.ArrayStart:
{
return this.ReadArray(typeIsHint ? null : expectedType);
}
case JsonToken.String:
{
return this.ReadString(typeIsHint ? null : expectedType);
}
case JsonToken.Number:
{
return this.ReadNumber(typeIsHint ? null : expectedType);
}
case JsonToken.False:
{
this.index += JsonReader.LiteralFalse.Length;
return false;
}
case JsonToken.True:
{
this.index += JsonReader.LiteralTrue.Length;
return true;
}
case JsonToken.Null:
{
this.index += JsonReader.LiteralNull.Length;
return null;
}
case JsonToken.NaN:
{
this.index += JsonReader.LiteralNotANumber.Length;
return Double.NaN;
}
case JsonToken.PositiveInfinity:
{
this.index += JsonReader.LiteralPositiveInfinity.Length;
return Double.PositiveInfinity;
}
case JsonToken.NegativeInfinity:
{
this.index += JsonReader.LiteralNegativeInfinity.Length;
return Double.NegativeInfinity;
}
case JsonToken.End:
default:
{
return null;
}
}
}
private object ReadObject(Type objectType)
{
if (this.Source[this.index] != JsonReader.OperatorObjectStart)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedObject, this.index);
}
Dictionary<string, MemberInfo> memberMap = null;
Object result;
if (objectType != null)
{
result = this.InstantiateObject(objectType, ref memberMap);
}
else
{
result = new Dictionary<String, Object>();
}
JsonToken token;
do
{
Type memberType;
MemberInfo memberInfo;
// consume opening brace or delim
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index);
}
// get next token
token = this.Tokenize();
if (token == JsonToken.ObjectEnd)
{
break;
}
if (token != JsonToken.String)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedPropertyName, this.index);
}
// parse object member value
string memberName = (String)this.ReadString(null);
// determine the type of the property/field
JsonReader.GetMemberInfo(memberMap, memberName, out memberType, out memberInfo);
// get next token
token = this.Tokenize();
if (token != JsonToken.NameDelim)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedPropertyNameDelim, this.index);
}
// consume delim
index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index);
}
// parse object member value
object value = this.Read(memberType, false);
if (result is IDictionary)
{
if (objectType == null &&
!String.IsNullOrEmpty(this.typeHintName) &&
this.typeHintName.Equals(memberName, StringComparison.InvariantCulture))
{
result = this.ProcessTypeHint(ref objectType, ref memberMap, (IDictionary)result, value as string);
}
else
{
((IDictionary)result)[memberName] = value;
}
}
else if (objectType.GetInterface(JsonWriter.TypeGenericIDictionary) != null)
{
throw new JsonDeserializationException(JsonReader.ErrorGenericIDictionary, this.index);
}
else
{
this.SetMemberValue(result, memberType, memberInfo, value);
}
// get next token
token = this.Tokenize();
} while (token == JsonToken.ValueDelim);
if (token != JsonToken.ObjectEnd)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index);
}
// consume closing brace
this.index++;
return result;
}
private Array ReadArray(Type arrayType)
{
if (this.Source[this.index] != JsonReader.OperatorArrayStart)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedArray, this.index);
}
bool isArrayTypeSet = (arrayType != null);
bool isArrayTypeAHint = !isArrayTypeSet;
if (isArrayTypeSet)
{
if (arrayType.HasElementType)
{
arrayType = arrayType.GetElementType();
}
else if (arrayType.IsGenericType)
{
Type[] generics = arrayType.GetGenericArguments();
if (generics.Length != 1)
{
// could use the first or last, but this more correct
arrayType = null;
}
else
{
arrayType = generics[0];
}
}
else
{
arrayType = null;
}
}
ArrayList jsArray = new ArrayList();
JsonToken token;
do
{
// consume opening bracket or delim
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedArray, this.index);
}
// get next token
token = this.Tokenize();
if (token == JsonToken.ArrayEnd)
{
break;
}
// parse array item
object value = this.Read(arrayType, isArrayTypeAHint);
jsArray.Add(value);
// establish if array is of common type
if (value == null)
{
if (arrayType != null && arrayType.IsValueType)
{
// use plain object to hold null
arrayType = null;
}
isArrayTypeSet = true;
}
else if (arrayType != null && !arrayType.IsAssignableFrom(value.GetType()))
{
// use plain object to hold value
arrayType = null;
isArrayTypeSet = true;
}
else if (!isArrayTypeSet)
{
// try out special type
// if hasn't been set before
arrayType = value.GetType();
isArrayTypeSet = true;
}
// get next token
token = this.Tokenize();
} while (token == JsonToken.ValueDelim);
if (token != JsonToken.ArrayEnd)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedArray, this.index);
}
// consume closing bracket
this.index++;
// check to see if all the same type and convert to that
if (arrayType != null && arrayType != typeof(object))
{
return jsArray.ToArray(arrayType);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -