/// <summary> /// Read JSON Array value. /// </summary> /// <param name="jsonReader">The <see cref="IJsonReader"/> to read from.</param> /// <returns>The <see cref="JsonArrayValue"/> generated.</returns> public static JsonArrayValue ReadAsArray(this IJsonReader jsonReader) { EdmUtil.CheckArgumentNull(jsonReader, "jsonReader"); // Supports to read from Begin if (jsonReader.NodeKind == JsonNodeKind.None) { jsonReader.Read(); } // Make sure the input is an Array jsonReader.ValidateNodeKind(JsonNodeKind.StartArray); JsonArrayValue arrayValue = new JsonArrayValue(); // Consume the "[" tag. jsonReader.Read(); while (jsonReader.NodeKind != JsonNodeKind.EndArray) { arrayValue.Add(jsonReader.ReadAsJsonValue()); } // Consume the "]" tag. jsonReader.Read(); return(arrayValue); }
public override void FromJsonData(IJsonReader reader) { var propertyName = reader.Value as string; switch (propertyName) { case "id": this.Id = reader.Read <Guid?>(null); break; case "name": this.Name = reader.Read <string>(null); break; case "teamId": this.TeamId = reader.Read <Guid?>(null); break; case "fantasyPoints": this.FantasyPoints = reader.Read <int?>(null); break; default: reader.Read(); break; } }
public async Task <Response> Send() { try { var response = (HttpWebResponse)(await _request.GetResponseAsync()); using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return(new Response( (int)response.StatusCode, _jsonReaderBody.Read(await reader.ReadToEndAsync()), new Cookies(response.Cookies), new Header(response.Headers))); } } catch (WebException ex) when(ex.Response != null) { var response = (HttpWebResponse)ex.Response; using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { var responseStr = reader.ReadToEndAsync(); return(new Response( (int)response.StatusCode, _jsonReaderBody.Read(await responseStr), new Cookies(response.Cookies), new Header(response.Headers), error: await responseStr)); } } catch (Exception ex) { return(new Response(404, Body.Empty, Cookies.Empty, Header.Empty, ex.Message)); } }
private static bool JsonCouldBeFullyParsed(IJsonReader jsonReader, IJsonWriter jsonWriter, object result, string json) { try { AssertV2.IsFalse(string.IsNullOrEmpty(json), "Json isNullOrEmpty"); var input = jsonReader.Read <System.Collections.Generic.Dictionary <string, object> >(json); var parsed = jsonReader.Read <System.Collections.Generic.Dictionary <string, object> >(jsonWriter.Write(result)); AssertV2.IsNotNull(parsed, "parsed"); return(JsonCouldBeFullyParsed(jsonReader, result.GetType().Name, input, parsed, 0)); } catch (Exception e) { Log.e(new Exception("exception during parsing json=" + json, e)); } return(false); }
/// <summary> /// Reads the next node. Use this instead of the direct call to Read since this asserts that there actually is a next node. /// </summary> /// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param> /// <returns>The node type of the node that reader is positioned on after reading.</returns> internal static JsonNodeType ReadNext(this IJsonReader jsonReader) { Debug.Assert(jsonReader != null, "jsonReader != null"); #if DEBUG bool result = jsonReader.Read(); Debug.Assert(result, "JsonReader.Read returned false in an unexpected place."); #else jsonReader.Read(); #endif return(jsonReader.NodeType); }
/// <summary> /// Parses out a JSON false AST node with a jsonTextReader. /// </summary> /// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param> /// <returns>JSON true AST node</returns> private static FalseNode ParseFalseNode(IJsonReader jsonTextReader) { // consume the false token from the reader jsonTextReader.Read(); return(FalseNode.Create()); }
/// <summary> /// Skips over a JSON value (primitive, object or array). /// </summary> /// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param> /// <remarks> /// Pre-Condition: JsonNodeType.PrimitiveValue, JsonNodeType.StartArray or JsonNodeType.StartObject /// Post-Condition: JsonNodeType.PrimitiveValue, JsonNodeType.EndArray or JsonNodeType.EndObject /// </remarks> internal static void SkipValue(this IJsonReader jsonReader) { Debug.Assert(jsonReader != null, "jsonReader != null"); int depth = 0; do { switch (jsonReader.NodeType) { case JsonNodeType.StartArray: case JsonNodeType.StartObject: depth++; break; case JsonNodeType.EndArray: case JsonNodeType.EndObject: Debug.Assert(depth > 0, "Seen too many scope ends."); depth--; break; default: Debug.Assert( jsonReader.NodeType != JsonNodeType.EndOfInput, "We should not have reached end of input, since the scopes should be well formed. Otherwise JsonReader should have failed by now."); break; } }while (jsonReader.Read() && depth > 0); if (depth > 0) { // Not all open scopes were closed: // "Invalid JSON. Unexpected end of input was found in JSON content. Not all object and array scopes were closed." throw JsonReaderExtensions.CreateException(Strings.JsonReader_EndOfInputWithOpenScope); } }
/// <summary> /// Reads the value from the <paramref name="jsonReader"/> /// </summary> /// <param name="jsonReader">The <see cref="IJsonReader"/> to read from.</param> /// <returns>The <see cref="IJsonValue"/> read.</returns> public static IJsonValue ReadAsJsonValue(this IJsonReader jsonReader) { //EdmUtil.CheckArgumentNull(jsonReader, "jsonReader"); // Supports to read from Begin if (jsonReader.NodeKind == JsonNodeKind.None) { jsonReader.Read(); } // Be noted: Json reader already verifies that value should be 'start array, start object or primitive value' // For any others, Json reader throws. So we don't care about other Node types. Debug.Assert( jsonReader.NodeKind == JsonNodeKind.StartArray || jsonReader.NodeKind == JsonNodeKind.StartObject || jsonReader.NodeKind == JsonNodeKind.PrimitiveValue, "json reader node type should be either start array, start object, or primitive value"); if (jsonReader.NodeKind == JsonNodeKind.StartArray) { return(jsonReader.ReadAsArray()); } else if (jsonReader.NodeKind == JsonNodeKind.StartObject) { return(jsonReader.ReadAsObject()); } return(jsonReader.ReadAsPrimitive()); }
private static void RunReadBenchmark( Payload payload, bool useUtf8) { // Don't really need to test both serialization formats, since they are similiar. IJsonReader jsonReader = JsonReader.Create(payload.Binary); while (jsonReader.Read()) { // Materialize the value switch (jsonReader.CurrentTokenType) { case JsonTokenType.BeginArray: case JsonTokenType.EndArray: // Single byte tokens break; case JsonTokenType.String: UtfAnyString value = jsonReader.GetStringValue(); if (useUtf8) { Utf8String _ = value.ToUtf8String(); } else { string _ = value.ToString(); } break; default: throw new ArgumentException("$Unknown token type."); } } }
public static UniqueConfiguration ConvertUniqueConfiguration(UniqueConfigurationJsonNotation uniqueConfigurationJSONNotation) { Enum.TryParse <Method>(uniqueConfigurationJSONNotation.method, ignoreCase: true, out var method); return(new UniqueConfiguration( uniqueConfigurationJSONNotation.name, uniqueConfigurationJSONNotation.url, method, _readerHeader.Read(uniqueConfigurationJSONNotation.header?.ToString() ?? string.Empty), _readerCookies.Read(uniqueConfigurationJSONNotation.cookies?.ToString() ?? string.Empty), _readerQueryString.Read(uniqueConfigurationJSONNotation.query_string?.ToString() ?? string.Empty), _readerBody.Read(uniqueConfigurationJSONNotation.body?.ToString()?.Trim() ?? string.Empty), uniqueConfigurationJSONNotation.body?.ToString()?.Trim() ?? string.Empty, JSONToValidation(uniqueConfigurationJSONNotation.validation), uniqueConfigurationJSONNotation.Wait )); }
private static FloatNode ParseFloatNode(IJsonReader jsonTextReader, JsonTokenType jsonTokenType) { if (!jsonTextReader.TryGetBufferedRawJsonToken(out ReadOnlyMemory <byte> bufferedRawJsonToken)) { throw new InvalidOperationException("Failed to get the buffered raw json token."); } FloatNode floatNode; switch (jsonTokenType) { case JsonTokenType.Float32: floatNode = Float32Node.Create(bufferedRawJsonToken); break; case JsonTokenType.Float64: floatNode = Float64Node.Create(bufferedRawJsonToken); break; default: throw new ArgumentException($"Unknown {nameof(JsonTokenType)}: {jsonTokenType}"); } // consume the float from the reader jsonTextReader.Read(); return(floatNode); }
/// <summary> /// Parses out a JSON true AST node with a jsonTextReader. /// </summary> /// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param> /// <returns>JSON true AST node</returns> private static TrueNode ParseTrueNode(IJsonReader jsonTextReader) { // consume the true token from the reader jsonTextReader.Read(); return(TrueNode.Create()); }
/// <summary> /// Parses out a JSON null AST node with a jsonTextReader. /// </summary> /// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param> /// <returns>JSON null AST node</returns> private static NullNode ParseNullNode(IJsonReader jsonTextReader) { // consume the null token from the reader jsonTextReader.Read(); return(NullNode.Create()); }
private static JsonObject ParseObject(this IJsonReader reader) { var obj = new JsonObject(); while (reader.Read() != Json.Token.EndOfFile) { if (reader.CurrentToken == Json.Token.ObjectStart) { continue; } if (reader.CurrentToken == Json.Token.ObjectKey) { string?Key = (string?)reader.CurrentValue; if (Key != null) { IJsonValue?Value = reader.ParseValue(); obj.Add(Key, Value); } } else if (reader.CurrentToken == Json.Token.ObjectEnd) { break; } } return(obj); }
private static FloatNode ParseFloatNode(IJsonReader jsonTextReader, JsonTokenType jsonTokenType) { ReadOnlyMemory <byte> bytes = jsonTextReader.GetBufferedRawJsonToken(); FloatNode floatNode; switch (jsonTokenType) { case JsonTokenType.Float32: floatNode = Float32Node.Create(bytes); break; case JsonTokenType.Float64: floatNode = Float64Node.Create(bytes); break; default: throw new ArgumentException($"Unknown {nameof(JsonTokenType)}: {jsonTokenType}"); } // consume the float from the reader jsonTextReader.Read(); return(floatNode); }
public static T GetResult <T>(this UnityWebRequest self, IJsonReader r) { AssertV2.IsTrue(self.isDone, "web request was not done!"); if (TypeCheck.AreEqual <T, UnityWebRequest>()) { return((T)(object)self); } if (typeof(Texture2D).IsCastableTo(typeof(T))) { AssertV2.IsTrue(self.downloadHandler is DownloadHandlerTexture, "self.downloadHandler was not a DownloadHandlerTexture"); var h = (DownloadHandlerTexture)self.downloadHandler; return((T)(object)h.texture); } if (TypeCheck.AreEqual <T, Stream>()) { return((T)(object)new MemoryStream(self.downloadHandler.data)); } if (TypeCheck.AreEqual <T, byte[]>()) { return((T)(object)self.downloadHandler.data); } if (TypeCheck.AreEqual <T, Headers>()) { return((T)(object)self.GetResponseHeadersV2()); } var text = self.downloadHandler.text; if (TypeCheck.AreEqual <T, string>()) { return((T)(object)text); } return(r.Read <T>(text)); }
protected override DoNext performInvoke() { var input = _reader.Read <T>(); _request.Set(input); return(DoNext.Continue); }
private static BinaryNode ParseBinaryNode(IJsonReader jsonTextReader) { BinaryNode node = BinaryNode.Create(jsonTextReader.GetBufferedRawJsonToken()); // advance the reader forward. jsonTextReader.Read(); return(node); }
/// <summary> /// Reads the next node from the <paramref name="jsonReader"/> and verifies that it is of the expected node type. /// </summary> /// <param name="jsonReader">The <see cref="JsonReader"/> to read from.</param> /// <param name="expectedNodeType">The expected <see cref="JsonNodeType"/> of the read node.</param> private static void ReadNext(this IJsonReader jsonReader, JsonNodeType expectedNodeType) { Debug.Assert(jsonReader != null, "jsonReader != null"); Debug.Assert(expectedNodeType != JsonNodeType.None, "expectedNodeType != JsonNodeType.None"); jsonReader.ValidateNodeType(expectedNodeType); jsonReader.Read(); }
/// <summary> /// Parses out a JSON array AST node with a jsonTextReader. /// </summary> /// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param> /// <returns>JSON array AST node</returns> private static ArrayNode ParseArrayNode(IJsonReader jsonTextReader) { List <JsonTextNode> items = new List <JsonTextNode>(); // consume the begin array token jsonTextReader.Read(); while (jsonTextReader.CurrentTokenType != JsonTokenType.EndArray) { items.Add(Parser.ParseNode(jsonTextReader)); } // consume the end array token jsonTextReader.Read(); return(ArrayNode.Create(items)); }
private object InternalGet(string key, object defaultValue) { if (!PlayerPrefs.HasKey(key)) { return(defaultValue); } return(jsonReader.Read <ValueWrapper>(PlayerPrefs.GetString(key)).value); }
private T InternalGet <T>(string key, T defaultValue) { if (!PlayerPrefs.HasKey(key)) { return(defaultValue); } return(jsonReader.Read <ValueWrapper>(PlayerPrefs.GetString(key)).GetValueAs <T>()); }
internal static JsonTokenInfo[] GetTokensWithReader(IJsonReader jsonReader) { List <JsonTokenInfo> tokens = new List <JsonTokenInfo>(); while (jsonReader.Read()) { switch (jsonReader.CurrentTokenType) { case JsonTokenType.NotStarted: throw new InvalidOperationException(); case JsonTokenType.BeginArray: tokens.Add(JsonTokenInfo.ArrayStart()); break; case JsonTokenType.EndArray: tokens.Add(JsonTokenInfo.ArrayEnd()); break; case JsonTokenType.BeginObject: tokens.Add(JsonTokenInfo.ObjectStart()); break; case JsonTokenType.EndObject: tokens.Add(JsonTokenInfo.ObjectEnd()); break; case JsonTokenType.String: tokens.Add(JsonTokenInfo.String(jsonReader.GetStringValue())); break; case JsonTokenType.Number: tokens.Add(JsonTokenInfo.Number(jsonReader.GetNumberValue())); break; case JsonTokenType.True: tokens.Add(JsonTokenInfo.Boolean(true)); break; case JsonTokenType.False: tokens.Add(JsonTokenInfo.Boolean(false)); break; case JsonTokenType.Null: tokens.Add(JsonTokenInfo.Null()); break; case JsonTokenType.FieldName: tokens.Add(JsonTokenInfo.FieldName(jsonReader.GetStringValue())); break; default: break; } } return(tokens.ToArray()); }
public static JsonToken[] Tokenize(IJsonReader jsonReader, string json) { List <JsonToken> tokensFromReader = new List <JsonToken>(); while (jsonReader.Read()) { switch (jsonReader.CurrentTokenType) { case JsonTokenType.NotStarted: throw new ArgumentException(string.Format("Got an unexpected JsonTokenType: {0} as an expected token type", jsonReader.CurrentTokenType)); case JsonTokenType.BeginArray: tokensFromReader.Add(JsonToken.ArrayStart()); break; case JsonTokenType.EndArray: tokensFromReader.Add(JsonToken.ArrayEnd()); break; case JsonTokenType.BeginObject: tokensFromReader.Add(JsonToken.ObjectStart()); break; case JsonTokenType.EndObject: tokensFromReader.Add(JsonToken.ObjectEnd()); break; case JsonTokenType.String: tokensFromReader.Add(JsonToken.String(jsonReader.GetStringValue())); break; case JsonTokenType.Number: tokensFromReader.Add(JsonToken.Number(jsonReader.GetNumberValue())); break; case JsonTokenType.True: tokensFromReader.Add(JsonToken.Boolean(true)); break; case JsonTokenType.False: tokensFromReader.Add(JsonToken.Boolean(false)); break; case JsonTokenType.Null: tokensFromReader.Add(JsonToken.Null()); break; case JsonTokenType.FieldName: tokensFromReader.Add(JsonToken.FieldName(jsonReader.GetStringValue())); break; default: break; } } return(tokensFromReader.ToArray()); }
public override void FromJsonData(IJsonReader reader) { var propertyName = reader.Value as string; switch (propertyName) { case "gameId": this.GameId = reader.Read <Guid?>(null); break; case "gameName": this.GameName = reader.Read <string>(null); break; case "awayTeamId": this.AwayTeamId = reader.Read <Guid?>(null); break; case "homeTeamId": this.HomeTeamId = reader.Read <Guid?>(null); break; case "quarter": this.Quarter = reader.Read <int?>(null); break; case "gameClock": this.GameClock = reader.Read <string>(null); break; default: reader.Read(); break; } }
/// <summary> /// Parses out a JSON object AST node with a jsonTextReader. /// </summary> /// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param> /// <returns>JSON object AST node</returns> private static ObjectNode ParseObjectNode(IJsonReader jsonTextReader) { List <ObjectProperty> properties = new List <ObjectProperty>(); // consume the begin object token jsonTextReader.Read(); while (jsonTextReader.CurrentTokenType != JsonTokenType.EndObject) { ObjectProperty property = Parser.ParsePropertyNode(jsonTextReader); properties.Add(property); } // consume the end object token jsonTextReader.Read(); return(ObjectNode.Create(properties)); }
/// <summary> /// Ensure next token is end object. /// </summary> /// <param name="reader">The json reader.</param> private static void EnsureEndObject(IJsonReader reader) { if (!reader.IsEndObject) { throw new InvalidOperationException("Invalid json token. Expect end object"); } reader.Read(); }
/// <summary> /// Parses out a JSON number AST node with a jsonTextReader. /// </summary> /// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param> /// <returns>JSON number AST node</returns> private static NumberNode ParseNumberNode(IJsonReader jsonTextReader) { NumberNode numberNode = NumberNode.Create(jsonTextReader.GetBufferedRawJsonToken()); // consume the number from the reader jsonTextReader.Read(); return(numberNode); }
/// <summary> /// Ensure next token is end array. /// </summary> /// <param name="reader">The json reader.</param> private static void EnsureEndArray(IJsonReader reader) { if (!reader.IsEndArray) { throw new InvalidOperationException("Invalid json token. Expect end array"); } reader.Read(); }
/// <summary> /// Parses out a JSON string AST node with a jsonTextReader. /// </summary> /// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param> /// <returns>JSON string AST node</returns> private static StringNode ParseStringNode(IJsonReader jsonTextReader) { StringNode stringNode = StringNode.Create(jsonTextReader.GetBufferedRawJsonToken()); // consume the string from the reader jsonTextReader.Read(); return(stringNode); }