예제 #1
0
        /// <summary>
        /// Loads a <see cref="JConstructor"/> from a <see cref="JsonReader"/>.
        /// </summary>
        /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JConstructor"/>.</param>
        /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON.
        /// If this is <c>null</c>, default load settings will be used.</param>
        /// <returns>A <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
        public new static JConstructor Load(JsonReader reader, JsonLoadSettings settings)
        {
            if (reader.TokenType == JsonToken.None)
            {
                if (!reader.Read())
                {
                    throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader.");
                }
            }

            reader.MoveToContent();

            if (reader.TokenType != JsonToken.StartConstructor)
            {
                throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

            JConstructor c = new JConstructor((string)reader.Value);

            c.SetLineInfo(reader as IJsonLineInfo, settings);

            c.ReadTokenFrom(reader, settings);

            return(c);
        }
예제 #2
0
        /// <summary>
        /// Asynchronously creates a <see cref="JToken"/> from a <see cref="JsonReader"/>.
        /// </summary>
        /// <param name="reader">An <see cref="JsonReader"/> positioned at the token to read into this <see cref="JToken"/>.</param>
        /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON.
        /// If this is <c>null</c>, default load settings will be used.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>
        /// A <see cref="Task{TResult}"/> that represents the asynchronous creation. The
        /// <see cref="Task{TResult}.Result"/> property returns a <see cref="JToken"/> that contains
        /// the token and its descendant tokens
        /// that were read from the reader. The runtime type of the token is determined
        /// by the token type of the first token encountered in the reader.
        /// </returns>
        public static async Task <JToken> ReadFromAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            ValidationUtils.ArgumentNotNull(reader, nameof(reader));

            if (reader.TokenType == JsonToken.None)
            {
                if (!await(settings != null && settings.CommentHandling == CommentHandling.Ignore ? reader.ReadAndMoveToContentAsync(cancellationToken) : reader.ReadAsync(cancellationToken)).ConfigureAwait(false))
                {
                    throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader.");
                }
            }

            IJsonLineInfo lineInfo = reader as IJsonLineInfo;

            switch (reader.TokenType)
            {
            case JsonToken.StartObject:
                return(await JObject.LoadAsync(reader, settings, cancellationToken).ConfigureAwait(false));

            case JsonToken.StartArray:
                return(await JArray.LoadAsync(reader, settings, cancellationToken).ConfigureAwait(false));

            case JsonToken.StartConstructor:
                return(await JConstructor.LoadAsync(reader, settings, cancellationToken).ConfigureAwait(false));

            case JsonToken.PropertyName:
                return(await JProperty.LoadAsync(reader, settings, cancellationToken).ConfigureAwait(false));

            case JsonToken.String:
            case JsonToken.Integer:
            case JsonToken.Float:
            case JsonToken.Date:
            case JsonToken.Boolean:
            case JsonToken.Bytes:
                JValue v = new JValue(reader.Value);
                v.SetLineInfo(lineInfo, settings);
                return(v);

            case JsonToken.Comment:
                v = JValue.CreateComment(reader.Value.ToString());
                v.SetLineInfo(lineInfo, settings);
                return(v);

            case JsonToken.Null:
                v = JValue.CreateNull();
                v.SetLineInfo(lineInfo, settings);
                return(v);

            case JsonToken.Undefined:
                v = JValue.CreateUndefined();
                v.SetLineInfo(lineInfo, settings);
                return(v);

            default:
                throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader. Unexpected token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }
        }
예제 #3
0
        /// <summary>
        /// Load a <see cref="JArray"/> from a string that contains JSON.
        /// </summary>
        /// <param name="json">A <see cref="String"/> that contains JSON.</param>
        /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON.
        /// If this is <c>null</c>, default load settings will be used.</param>
        /// <returns>A <see cref="JArray"/> populated from the string that contains JSON.</returns>
        /// <example>
        ///   <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParseArray" title="Parsing a JSON Array from Text" />
        /// </example>
        public new static JArray Parse(string json, JsonLoadSettings settings)
        {
            using (JsonReader reader = new JsonTextReader(new StringReader(json)))
            {
                JArray a = Load(reader, settings);

                while (reader.Read())
                {
                    // Any content encountered here other than a comment will throw in the reader.
                }

                return(a);
            }
        }
예제 #4
0
        internal async Task ReadTokenFromAsync(JsonReader reader, JsonLoadSettings options, CancellationToken cancellationToken = default(CancellationToken))
        {
            ValidationUtils.ArgumentNotNull(reader, nameof(reader));
            int startDepth = reader.Depth;

            if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
            {
                throw JsonReaderException.Create(reader, "Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
            }

            await ReadContentFromAsync(reader, options, cancellationToken).ConfigureAwait(false);

            if (reader.Depth > startDepth)
            {
                throw JsonReaderException.Create(reader, "Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
            }
        }
예제 #5
0
        internal void ReadTokenFrom(JsonReader reader, JsonLoadSettings options)
        {
            int startDepth = reader.Depth;

            if (!reader.Read())
            {
                throw JsonReaderException.Create(reader, "Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
            }

            ReadContentFrom(reader, options);

            int endDepth = reader.Depth;

            if (endDepth > startDepth)
            {
                throw JsonReaderException.Create(reader, "Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
            }
        }
예제 #6
0
        internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings)
        {
            ValidationUtils.ArgumentNotNull(r, nameof(r));
            IJsonLineInfo lineInfo = r as IJsonLineInfo;

            JContainer parent = this;

            do
            {
                if ((parent as JProperty)?.Value != null)
                {
                    if (parent == this)
                    {
                        return;
                    }

                    parent = parent.Parent;
                }

                switch (r.TokenType)
                {
                case JsonToken.None:
                    // new reader. move to actual content
                    break;

                case JsonToken.StartArray:
                    JArray a = new JArray();
                    a.SetLineInfo(lineInfo, settings);
                    parent.Add(a);
                    parent = a;
                    break;

                case JsonToken.EndArray:
                    if (parent == this)
                    {
                        return;
                    }

                    parent = parent.Parent;
                    break;

                case JsonToken.StartObject:
                    JObject o = new JObject();
                    o.SetLineInfo(lineInfo, settings);
                    parent.Add(o);
                    parent = o;
                    break;

                case JsonToken.EndObject:
                    if (parent == this)
                    {
                        return;
                    }

                    parent = parent.Parent;
                    break;

                case JsonToken.StartConstructor:
                    JConstructor constructor = new JConstructor(r.Value.ToString());
                    constructor.SetLineInfo(lineInfo, settings);
                    parent.Add(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:
                case JsonToken.Bytes:
                    JValue v = new JValue(r.Value);
                    v.SetLineInfo(lineInfo, settings);
                    parent.Add(v);
                    break;

                case JsonToken.Comment:
                    if (settings != null && settings.CommentHandling == CommentHandling.Load)
                    {
                        v = JValue.CreateComment(r.Value.ToString());
                        v.SetLineInfo(lineInfo, settings);
                        parent.Add(v);
                    }
                    break;

                case JsonToken.Null:
                    v = JValue.CreateNull();
                    v.SetLineInfo(lineInfo, settings);
                    parent.Add(v);
                    break;

                case JsonToken.Undefined:
                    v = JValue.CreateUndefined();
                    v.SetLineInfo(lineInfo, settings);
                    parent.Add(v);
                    break;

                case JsonToken.PropertyName:
                    string    propertyName = r.Value.ToString();
                    JProperty property     = new JProperty(propertyName);
                    property.SetLineInfo(lineInfo, settings);
                    JObject parentObject = (JObject)parent;
                    // handle multiple properties with the same name in JSON
                    JProperty existingPropertyWithName = parentObject.Property(propertyName);
                    if (existingPropertyWithName == null)
                    {
                        parent.Add(property);
                    }
                    else
                    {
                        existingPropertyWithName.Replace(property);
                    }
                    parent = property;
                    break;

                default:
                    throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(CultureInfo.InvariantCulture, r.TokenType));
                }
            } while (r.Read());
        }
예제 #7
0
 /// <summary>
 /// Asynchronously creates a <see cref="JToken"/> from a <see cref="JsonReader"/>.
 /// </summary>
 /// <param name="reader">A <see cref="JsonReader"/> positioned at the token to read into this <see cref="JToken"/>.</param>
 /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON.
 /// If this is <c>null</c>, default load settings will be used.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
 /// <returns>
 /// A <see cref="Task{TResult}"/> that represents the asynchronous creation. The <see cref="Task{TResult}.Result"/>
 /// property returns a <see cref="JToken"/> that contains the token and its descendant tokens
 /// that were read from the reader. The runtime type of the token is determined
 /// by the token type of the first token encountered in the reader.
 /// </returns>
 public static Task <JToken> LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(ReadFromAsync(reader, settings, cancellationToken));
 }