public static CosmosElement Dispatch( IJsonNavigator jsonNavigator, IJsonNavigatorNode jsonNavigatorNode) { JsonNodeType jsonNodeType = jsonNavigator.GetNodeType(jsonNavigatorNode); return(jsonNodeType switch { JsonNodeType.Null => CosmosNull.Create(), JsonNodeType.False => CosmosBoolean.Create(false), JsonNodeType.True => CosmosBoolean.Create(true), JsonNodeType.Number64 => CosmosNumber64.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.FieldName => CosmosString.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.String => CosmosString.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.Array => CosmosArray.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.Object => CosmosObject.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.Int8 => CosmosInt8.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.Int16 => CosmosInt16.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.Int32 => CosmosInt32.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.Int64 => CosmosInt64.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.UInt32 => CosmosUInt32.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.Float32 => CosmosFloat32.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.Float64 => CosmosFloat64.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.Guid => CosmosGuid.Create(jsonNavigator, jsonNavigatorNode), JsonNodeType.Binary => CosmosBinary.Create(jsonNavigator, jsonNavigatorNode), _ => throw new ArgumentException($"Unknown {nameof(JsonNodeType)}: {jsonNodeType}") });
public JsonNode GetAttribute(string attributeName, bool forceCreate = false) { if (_childs == null && attributeName == null || attributeName.Length <= 0) { return(null); } JsonNode result = null; if (_nodeType == JsonNodeType.Object) { result = FindChildNode(attributeName); } if (forceCreate && result == null) { if (_nodeType != JsonNodeType.Object) { ReleaseData(); _nodeType = JsonNodeType.Object; } result = new JsonNode(); result.Name = attributeName; if (_childs == null) { _childs = new List <JsonNode>(); } _childs.Add(result); } return(result); }
/// <summary> /// Constructor. /// </summary> /// <param name="nodeType">The type of the node read.</param> /// <param name="value">The value of the node.</param> internal BufferedNode(JsonNodeType nodeType, object value) { this.nodeType = nodeType; this.nodeValue = value; this.Previous = this; this.Next = this; }
private static void ValidateNodeType(this JsonReader jsonReader, JsonNodeType expectedNodeType) { if (jsonReader.NodeType != expectedNodeType) { throw CreateException(Strings.JsonReaderExtensions_UnexpectedNodeDetected(expectedNodeType, jsonReader.NodeType)); } }
private static ReadOnlyMemory <byte> GetNodeOfType( JsonNodeType expected, IJsonNavigatorNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (!(node is BinaryNavigatorNode binaryNavigatorNode)) { throw new ArgumentException($"{nameof(node)} must be a {nameof(BinaryNavigatorNode)}"); } ReadOnlyMemory <byte> buffer = binaryNavigatorNode.Buffer; if (buffer.Length == 0) { throw new ArgumentException($"Node must not be empty."); } JsonNodeType actual = NodeTypes.GetNodeType(buffer.Span[0]); if (actual != expected) { throw new ArgumentException($"Node needs to be of type {expected}."); } return(buffer); }
public LazyCosmosObject(IJsonNavigator jsonNavigator, IJsonNavigatorNode jsonNavigatorNode) { JsonNodeType type = jsonNavigator.GetNodeType(jsonNavigatorNode); if (type != JsonNodeType.Object) { throw new ArgumentOutOfRangeException($"{nameof(jsonNavigatorNode)} must be a {JsonNodeType.Object} node. Got {type} instead."); } this.jsonNavigator = jsonNavigator; this.jsonNavigatorNode = jsonNavigatorNode; this.lazyCache = new Lazy <Dictionary <string, CosmosElement> >(() => { int propertyCount = this.jsonNavigator.GetObjectPropertyCount(this.jsonNavigatorNode); Dictionary <string, CosmosElement> cache = new Dictionary <string, CosmosElement>(capacity: propertyCount); foreach (ObjectProperty objectProperty in this.jsonNavigator.GetObjectProperties(this.jsonNavigatorNode)) { string key = this.jsonNavigator.GetStringValue(objectProperty.NameNode); CosmosElement value = CosmosElement.Dispatch(this.jsonNavigator, objectProperty.ValueNode); cache[key] = value; } return(cache); }); }
public LazyCosmosString(IJsonNavigator jsonNavigator, IJsonNavigatorNode jsonNavigatorNode) { if (jsonNavigator == null) { throw new ArgumentNullException($"{nameof(jsonNavigator)}"); } if (jsonNavigatorNode == null) { throw new ArgumentNullException($"{nameof(jsonNavigatorNode)}"); } JsonNodeType type = jsonNavigator.GetNodeType(jsonNavigatorNode); if (type != JsonNodeType.String) { throw new ArgumentOutOfRangeException($"{nameof(jsonNavigatorNode)} must be a {JsonNodeType.String} node. Got {type} instead."); } this.jsonNavigator = jsonNavigator; this.jsonNavigatorNode = jsonNavigatorNode; this.lazyString = new Lazy <string>(() => { return(this.jsonNavigator.GetStringValue(this.jsonNavigatorNode)); }); }
private bool TryReadString(out object value, out JsonNodeType nodeType) { var sb = new StringBuilder(38); // Large enough to read a DateTime or Guid. while (true) { var read = ReadCurrent(); switch (read) { case '"': value = sb.ToString(); nodeType = JsonNodeType.String; return(true); case '\\': sb.Append(ReadEscapedChar()); break; case -1: value = sb.Insert(0, '"').ToString(); nodeType = JsonNodeType.Invalid; return(false); default: sb.Append((char)read); break; } } }
public LazyCosmosNumber64( IJsonNavigator jsonNavigator, IJsonNavigatorNode jsonNavigatorNode) { if (jsonNavigator == null) { throw new ArgumentNullException($"{nameof(jsonNavigator)}"); } if (jsonNavigatorNode == null) { throw new ArgumentNullException($"{nameof(jsonNavigatorNode)}"); } JsonNodeType type = jsonNavigator.GetNodeType(jsonNavigatorNode); if (type != JsonNodeType.Number) { throw new ArgumentOutOfRangeException($"{nameof(jsonNavigatorNode)} must be a {JsonNodeType.Number} node. Got {type} instead."); } this.jsonNavigator = jsonNavigator; this.jsonNavigatorNode = jsonNavigatorNode; this.lazyNumber = new Lazy <double>(() => { return(this.jsonNavigator.GetNumberValue(this.jsonNavigatorNode)); }); }
public LazyCosmosArray( IJsonNavigator jsonNavigator, IJsonNavigatorNode jsonNavigatorNode) { JsonNodeType type = jsonNavigator.GetNodeType(jsonNavigatorNode); if (type != JsonNodeType.Array) { throw new ArgumentOutOfRangeException($"{nameof(jsonNavigatorNode)} must be an {JsonNodeType.Array} node. Got {type} instead."); } this.jsonNavigator = jsonNavigator; this.jsonNavigatorNode = jsonNavigatorNode; this.lazyCosmosElementArray = new Lazy <Lazy <CosmosElement>[]>(() => { Lazy <CosmosElement>[] lazyArray = new Lazy <CosmosElement> [this.jsonNavigator.GetArrayItemCount(this.jsonNavigatorNode)]; int index = 0; // Using foreach instead of indexer, since the navigator doesn't support random seeks efficiently. foreach (IJsonNavigatorNode arrayItem in this.jsonNavigator.GetArrayItems(this.jsonNavigatorNode)) { lazyArray[index] = new Lazy <CosmosElement>(() => CosmosElement.Dispatch(this.jsonNavigator, arrayItem)); index++; } return(lazyArray); }); }
public LazyCosmosBinary( IJsonNavigator jsonNavigator, IJsonNavigatorNode jsonNavigatorNode) { JsonNodeType type = jsonNavigator.GetNodeType(jsonNavigatorNode); if (type != JsonNodeType.Binary) { throw new ArgumentOutOfRangeException($"{nameof(jsonNavigatorNode)} must be a {JsonNodeType.Binary} node. Got {type} instead."); } this.jsonNavigator = jsonNavigator; this.jsonNavigatorNode = jsonNavigatorNode; this.lazyBytes = new Lazy <ReadOnlyMemory <byte> >(() => { if (!this.jsonNavigator.TryGetBufferedBinaryValue( this.jsonNavigatorNode, out ReadOnlyMemory <byte> bufferedBinaryValue)) { bufferedBinaryValue = this.jsonNavigator.GetBinaryValue( this.jsonNavigatorNode); } return(bufferedBinaryValue); }); }
void CheckAdd(JsonNodeType type) { // can add anything to object type if (Type == JsonNodeType.Object) { return; } switch (type) { case JsonNodeType.Object: case JsonNodeType.Value: // can add value to array if (Type == JsonNodeType.Array) { return; } // can add value to value container if (Type == JsonNodeType.Value) { return; } break; } throw new ArgumentException(string.Format("Cannot add item of type {0} to an JsonObject of type {1}!", type, Type)); }
public BinaryNavigatorNode( ReadOnlyMemory <byte> buffer, JsonNodeType jsonNodeType) { this.Buffer = buffer; this.JsonNodeType = jsonNodeType; }
public LazyCosmosBinary(IJsonNavigator jsonNavigator, IJsonNavigatorNode jsonNavigatorNode) { if (jsonNavigator == null) { throw new ArgumentNullException($"{nameof(jsonNavigator)}"); } if (jsonNavigatorNode == null) { throw new ArgumentNullException($"{nameof(jsonNavigatorNode)}"); } JsonNodeType type = jsonNavigator.GetNodeType(jsonNavigatorNode); if (type != JsonNodeType.Binary) { throw new ArgumentOutOfRangeException($"{nameof(jsonNavigatorNode)} must be a {JsonNodeType.Binary} node. Got {type} instead."); } this.jsonNavigator = jsonNavigator; this.jsonNavigatorNode = jsonNavigatorNode; this.lazyBytes = new Lazy <IReadOnlyList <byte> >(() => { return(this.jsonNavigator.GetBinaryValue(this.jsonNavigatorNode)); }); }
/// <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 JsonReader jsonReader, JsonNodeType expectedNodeType) { Debug.Assert(jsonReader != null, "jsonReader != null"); Debug.Assert(expectedNodeType != JsonNodeType.None, "expectedNodeType != JsonNodeType.None"); jsonReader.ValidateNodeType(expectedNodeType); jsonReader.Read(); }
public bool Read(JsonNodeType nodeType) { // validate node type this.Validate(NodeType); // read return(this.Read()); }
void Check2( JsonNode n, bool isNull, bool isArray, bool isObject, bool isValue, JsonNodeType valueType, bool valueBoolean, int valueInt32, long valueInt64, double valueNumber, string valueString) { CheckInternal(n, isNull, isArray, isObject, isValue, valueType, valueBoolean, valueInt32, valueInt64, valueNumber, valueString); CheckInternal(n.AsString, isNull, isArray, isObject, isValue, JsonNodeType.String, valueBoolean, valueInt32, valueInt64, valueNumber, valueString); }
/// <summary> /// Determines if the reader is on a value node. /// </summary> /// <param name="jsonReader">The reader to inspect.</param> /// <returns>true if the reader is on PrimitiveValue, StartObject or StartArray node, false otherwise.</returns> internal static bool IsOnValueNode(this JsonReader jsonReader) { DebugUtils.CheckNoExternalCallers(); JsonNodeType nodeType = jsonReader.NodeType; return(nodeType == JsonNodeType.PrimitiveValue || nodeType == JsonNodeType.StartObject || nodeType == JsonNodeType.StartArray); }
private void Nest(JsonNodeType type) { Nesting.Push(new JsonWriterState(type)); if (0 != Settings.Indent.Length) { Indent += Settings.Indent; } }
/// <summary> /// Asynchronously 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 async Task ReadNextAsync(this IJsonReaderAsync jsonReader, JsonNodeType expectedNodeType) { Debug.Assert(jsonReader != null, "jsonReader != null"); Debug.Assert(expectedNodeType != JsonNodeType.None, "expectedNodeType != JsonNodeType.None"); jsonReader.ValidateNodeType(expectedNodeType); await jsonReader.ReadAsync().ConfigureAwait(false); }
public void SetNullValue() { if (_nodeType != JsonNodeType.NullValue) { ReleaseData(); _nodeType = JsonNodeType.NullValue; } }
private JsonNodeType ExitScope() { JsonNodeType jsonNodeType = scopes[depth]; scopes[depth] = JsonNodeType.None; --depth; return(jsonNodeType); }
private bool EndOfInput() { if (this.scopes.Count > 1) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_EndOfInputWithOpenScope); } this.nodeType = JsonNodeType.EndOfInput; return(false); }
public void SetNumberValue(double value) { if (_nodeType != JsonNodeType.NumberValue) { ReleaseData(); _nodeType = JsonNodeType.NumberValue; } _doubleValue = value; }
public void SetObjectValue(JsonNode objNode) { if (_nodeType != JsonNodeType.ObjectValue) { ReleaseData(); _nodeType = JsonNodeType.ObjectValue; } _objectValue = objNode; }
public void SetBoolValue(bool value) { if (_nodeType != JsonNodeType.BooleanValue) { ReleaseData(); _nodeType = JsonNodeType.BooleanValue; } _longValue = (value) ? 1 : 0; }
public void SetStringValue(string value) { if (_nodeType != JsonNodeType.StringValue) { ReleaseData(); _nodeType = JsonNodeType.StringValue; } _stringValue = value; }
/// <summary> /// Converts this node to an array. /// </summary> internal void ConvertToArray() { if ((content != null) || (Type != JsonNodeType.Object)) { throw new InvalidDataException(string.Format("Cannot convert type {0} to array!", Type)); } Type = JsonNodeType.Array; }
private bool EndOfInput() { if (this.scopes.Count > 1) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_EndOfInputWithOpenScope); } this.nodeType = JsonNodeType.EndOfInput; return false; }
public bool Read() { switch (callCount) { case 0: value = null; nodeType = JsonNodeType.StartObject; break; case 1: value = "@context"; nodeType = JsonNodeType.Property; break; case 2: value = "http://test/$metadata#People/$entity"; nodeType = JsonNodeType.PrimitiveValue; break; case 3: value = "PersonId"; nodeType = JsonNodeType.Property; break; case 4: value = 999; nodeType = JsonNodeType.PrimitiveValue; break; case 5: value = "Name"; nodeType = JsonNodeType.Property; break; case 6: value = "Jack"; nodeType = JsonNodeType.PrimitiveValue; break; case 7: value = null; nodeType = JsonNodeType.EndObject; break; case 8: value = null; nodeType = JsonNodeType.EndOfInput; return(false); default: return(false); } ++callCount; return(true); }
/// <summary> /// Validates that the reader is positioned on the specified node type. /// </summary> /// <param name="jsonReader">The <see cref="JsonReader"/> to use.</param> /// <param name="expectedNodeType">The expected node type.</param> private static void ValidateNodeType(this JsonReader jsonReader, JsonNodeType expectedNodeType) { Debug.Assert(jsonReader != null, "jsonReader != null"); Debug.Assert(expectedNodeType != JsonNodeType.None, "expectedNodeType != JsonNodeType.None"); if (jsonReader.NodeType != expectedNodeType) { throw CreateException(Strings.JsonReaderExtensions_UnexpectedNodeDetected(expectedNodeType, jsonReader.NodeType)); } }
private void CheckText(JsonNodeType nextNodeType) { if (this.IsClosed) { ThrowClosed(); } if (this.depth == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("XmlIllegalOutsideRoot"))); } if ((nextNodeType == JsonNodeType.StandaloneText) && (this.nodeType == JsonNodeType.QuotedText)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("JsonCannotWriteStandaloneTextAfterQuotedText"))); } }
private void CheckText(JsonNodeType nextNodeType) { if (IsClosed) { ThrowClosed(); } if (_depth == 0) { throw new InvalidOperationException(SR.XmlIllegalOutsideRoot); } if ((nextNodeType == JsonNodeType.StandaloneText) && (_nodeType == JsonNodeType.QuotedText)) { throw new XmlException(SR.JsonCannotWriteStandaloneTextAfterQuotedText); } }
internal JsonWriterState(JsonNodeType parent) { Parent = parent; }
public virtual bool Read() { this.nodeValue = null; if (!this.SkipWhitespaces()) { return this.EndOfInput(); } Scope scope = this.scopes.Peek(); bool flag = false; if (this.characterBuffer[this.tokenStartIndex] == ',') { flag = true; this.tokenStartIndex++; if (!this.SkipWhitespaces()) { return this.EndOfInput(); } } switch (scope.Type) { case ScopeType.Root: if (flag) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Root)); } if (scope.ValueCount > 0) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_MultipleTopLevelValues); } this.nodeType = this.ParseValue(); break; case ScopeType.Array: if (flag && (scope.ValueCount == 0)) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Array)); } if (this.characterBuffer[this.tokenStartIndex] == ']') { this.tokenStartIndex++; if (flag) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Array)); } this.PopScope(); this.nodeType = JsonNodeType.EndArray; } else { if (!flag && (scope.ValueCount > 0)) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_MissingComma(ScopeType.Array)); } this.nodeType = this.ParseValue(); } break; case ScopeType.Object: if (flag && (scope.ValueCount == 0)) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Object)); } if (this.characterBuffer[this.tokenStartIndex] == '}') { this.tokenStartIndex++; if (flag) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Object)); } this.PopScope(); this.nodeType = JsonNodeType.EndObject; } else { if (!flag && (scope.ValueCount > 0)) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_MissingComma(ScopeType.Object)); } this.nodeType = this.ParseProperty(); } break; case ScopeType.Property: if (flag) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Property)); } this.nodeType = this.ParseValue(); break; default: throw JsonReaderExtensions.CreateException(Strings.General_InternalError(InternalErrorCodes.JsonReader_Read)); } return true; }
void EnterJsonScope(JsonNodeType currentNodeType) { scopeDepth++; if (scopes == null) { scopes = new JsonNodeType[4]; } else if (scopes.Length == scopeDepth) { JsonNodeType[] newScopes = new JsonNodeType[scopeDepth * 2]; Array.Copy(scopes, newScopes, scopeDepth); scopes = newScopes; } scopes[scopeDepth] = currentNodeType; }
private void StartText() { if (HasOpenAttribute) { throw new InvalidOperationException(SR.JsonMustUseWriteStringForWritingAttributeValues); } if ((_dataType == JsonDataType.None) && (_serverTypeValue != null)) { throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString)); } if (IsWritingNameWithMapping && !WrittenNameWithMapping) { // Don't write out any text content unless the local name has been written. // Not providing a better error message because localization deadline has passed. throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.itemString, string.Empty, JsonGlobals.itemString)); } if ((_dataType == JsonDataType.String) || (_dataType == JsonDataType.None)) { CheckText(JsonNodeType.QuotedText); if (_nodeType != JsonNodeType.QuotedText) { WriteJsonQuote(); } _nodeType = JsonNodeType.QuotedText; } else if ((_dataType == JsonDataType.Number) || (_dataType == JsonDataType.Boolean)) { CheckText(JsonNodeType.StandaloneText); _nodeType = JsonNodeType.StandaloneText; } else { ThrowInvalidAttributeContent(); } }
public override void WriteStartElement(string prefix, string localName, string ns) { if (localName == null) { throw new ArgumentNullException(nameof(localName)); } if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName)); } if (!string.IsNullOrEmpty(prefix)) { if (string.IsNullOrEmpty(ns) || !TrySetWritingNameWithMapping(localName, ns)) { throw new ArgumentException(SR.Format(SR.JsonPrefixMustBeNullOrEmpty, prefix), nameof(prefix)); } } if (!string.IsNullOrEmpty(ns)) { if (!TrySetWritingNameWithMapping(localName, ns)) { throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, ns), nameof(ns)); } } if (IsClosed) { ThrowClosed(); } if (HasOpenAttribute) { throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteStartElement")); } if ((_nodeType != JsonNodeType.None) && _depth == 0) { throw new XmlException(SR.JsonMultipleRootElementsNotAllowedOnWriter); } switch (_nodeType) { case JsonNodeType.None: { if (!localName.Equals(JsonGlobals.rootString)) { throw new XmlException(SR.Format(SR.JsonInvalidRootElementName, localName, JsonGlobals.rootString)); } EnterScope(JsonNodeType.Element); break; } case JsonNodeType.Element: { if ((_dataType != JsonDataType.Array) && (_dataType != JsonDataType.Object)) { throw new XmlException(SR.JsonNodeTypeArrayOrObjectNotSpecified); } if (_indent) { WriteNewLine(); WriteIndent(); } if (!IsWritingCollection) { if (_nameState != NameState.IsWritingNameWithMapping) { WriteJsonElementName(localName); } } else if (!localName.Equals(JsonGlobals.itemString)) { throw new XmlException(SR.Format(SR.JsonInvalidItemNameForArrayElement, localName, JsonGlobals.itemString)); } EnterScope(JsonNodeType.Element); break; } case JsonNodeType.EndElement: { if (_endElementBuffer) { _nodeWriter.WriteText(JsonGlobals.MemberSeparatorChar); } if (_indent) { WriteNewLine(); WriteIndent(); } if (!IsWritingCollection) { if (_nameState != NameState.IsWritingNameWithMapping) { WriteJsonElementName(localName); } } else if (!localName.Equals(JsonGlobals.itemString)) { throw new XmlException(SR.Format(SR.JsonInvalidItemNameForArrayElement, localName, JsonGlobals.itemString)); } EnterScope(JsonNodeType.Element); break; } default: throw new XmlException(SR.JsonInvalidStartElementCall); } _isWritingDataTypeAttribute = false; _isWritingServerTypeAttribute = false; _isWritingXmlnsAttribute = false; _wroteServerTypeAttribute = false; _serverTypeValue = null; _dataType = JsonDataType.None; _nodeType = JsonNodeType.Element; }
public virtual bool Read() { // Reset the node value. this.nodeValue = null; #if DEBUG // Reset the node type to None - so that we can verify that the Read method actually sets it. this.nodeType = JsonNodeType.None; #endif // Skip any whitespace characters. // This also makes sure that we have at least one non-whitespace character available. if (!this.SkipWhitespaces()) { return this.EndOfInput(); } Debug.Assert( this.tokenStartIndex < this.storedCharacterCount && !IsWhitespaceCharacter(this.characterBuffer[this.tokenStartIndex]), "The SkipWhitespaces didn't correctly skip all whitespace characters from the input."); Scope currentScope = this.scopes.Peek(); bool commaFound = false; if (this.characterBuffer[this.tokenStartIndex] == ',') { commaFound = true; this.tokenStartIndex++; // Note that validity of the comma is verified below depending on the current scope. // Skip all whitespaces after comma. // Note that this causes "Unexpected EOF" error if the comma is the last thing in the input. // It might not be the best error message in certain cases, but it's still correct (a JSON payload can never end in comma). if (!this.SkipWhitespaces()) { return this.EndOfInput(); } Debug.Assert( this.tokenStartIndex < this.storedCharacterCount && !IsWhitespaceCharacter(this.characterBuffer[this.tokenStartIndex]), "The SkipWhitespaces didn't correctly skip all whitespace characters from the input."); } switch (currentScope.Type) { case ScopeType.Root: if (commaFound) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Root)); } if (currentScope.ValueCount > 0) { // We already found the top-level value, so fail throw JsonReaderExtensions.CreateException(Strings.JsonReader_MultipleTopLevelValues); } // We expect a "value" - start array, start object or primitive value this.nodeType = this.ParseValue(); break; case ScopeType.Array: if (commaFound && currentScope.ValueCount == 0) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Array)); } // We might see end of array here if (this.characterBuffer[this.tokenStartIndex] == ']') { this.tokenStartIndex++; // End of array is only valid when there was no comma before it. if (commaFound) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Array)); } this.PopScope(); this.nodeType = JsonNodeType.EndArray; break; } if (!commaFound && currentScope.ValueCount > 0) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_MissingComma(ScopeType.Array)); } // We expect element which is a "value" - start array, start object or primitive value this.nodeType = this.ParseValue(); break; case ScopeType.Object: if (commaFound && currentScope.ValueCount == 0) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Object)); } // We might see end of object here if (this.characterBuffer[this.tokenStartIndex] == '}') { this.tokenStartIndex++; // End of object is only valid when there was no comma before it. if (commaFound) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Object)); } this.PopScope(); this.nodeType = JsonNodeType.EndObject; break; } else { if (!commaFound && currentScope.ValueCount > 0) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_MissingComma(ScopeType.Object)); } // We expect a property here this.nodeType = this.ParseProperty(); break; } case ScopeType.Property: if (commaFound) { throw JsonReaderExtensions.CreateException(Strings.JsonReader_UnexpectedComma(ScopeType.Property)); } // We expect the property value, which is a "value" - start array, start object or primitive value this.nodeType = this.ParseValue(); break; default: #if SPATIAL throw JsonReaderExtensions.CreateException(Strings.JsonReader_InternalError); #else throw JsonReaderExtensions.CreateException(Strings.General_InternalError(InternalErrorCodes.JsonReader_Read)); #endif } Debug.Assert( this.nodeType != JsonNodeType.None && this.nodeType != JsonNodeType.EndOfInput, "Read should never go back to None and EndOfInput should be reported by directly returning."); return true; }
/// <summary> /// Constructor. /// </summary> /// <param name="reader">The text reader to read input characters from.</param> /// <param name="jsonFormat">The specific JSON-based format expected by the reader.</param> /// <param name="isIeee754Compatible">If it is isIeee754Compatible</param> public JsonReader(TextReader reader, ODataFormat jsonFormat, bool isIeee754Compatible) { Debug.Assert(reader != null, "reader != null"); Debug.Assert(jsonFormat == ODataFormat.Json, "Expected a json-based format to create a JsonReader"); this.nodeType = JsonNodeType.None; this.nodeValue = null; this.reader = reader; this.characterBuffer = new char[InitialCharacterBufferSize]; this.storedCharacterCount = 0; this.tokenStartIndex = 0; this.endOfInputReached = false; this.isIeee754Compatible = isIeee754Compatible; this.allowAnnotations = jsonFormat == ODataFormat.Json; this.scopes = new Stack<Scope>(); this.scopes.Push(new Scope(ScopeType.Root)); }
private void Pair(string name, string value, JsonNodeType type) { if (null == name) { throw new ArgumentNullException("name"); } if (JsonNodeType.Array == Nesting.Peek().Parent) { throw new InvalidOperationException("Named values cannot be added to an array."); } _writer.Write("{0}\"{1}\":{2}{3}".FormatWith(Punctuation, name, Settings.ColonPadding, value)); Nesting.Peek().Previous = type; }
private void End(char value, JsonNodeType previous) { Nesting.Pop(); Nesting.Peek().Previous = previous; if (0 != Settings.Indent.Length) { Indent.RemoveFromEnd(Settings.Indent); } _writer.Write("{0}{1}{2}".FormatWith(Settings.CommaPadding, Indent, value)); }
private void Array(string value, JsonNodeType type) { if (JsonNodeType.Array != Nesting.Peek().Parent) { throw new InvalidOperationException("Array values can only be added to an array."); } _writer.Write("{0}{1}".FormatWith(Punctuation, value)); Nesting.Peek().Previous = type; }
private void EnterScope(JsonNodeType currentNodeType) { _depth++; if (_scopes == null) { _scopes = new JsonNodeType[4]; } else if (_scopes.Length == _depth) { JsonNodeType[] newScopes = new JsonNodeType[_depth * 2]; Array.Copy(_scopes, 0, newScopes, 0, _depth); _scopes = newScopes; } _scopes[_depth] = currentNodeType; }
/// <summary> /// Constructor. /// </summary> /// <param name="reader">The text reader to read input characters from.</param> public JsonReader(TextReader reader) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(reader != null, "reader != null"); this.nodeType = JsonNodeType.None; this.nodeValue = null; this.reader = reader; this.characterBuffer = new char[InitialCharacterBufferSize]; this.storedCharacterCount = 0; this.tokenStartIndex = 0; this.endOfInputReached = false; this.scopes = new Stack<Scope>(); this.scopes.Push(new Scope(ScopeType.Root)); }
private void InitializeWriter() { _nodeType = JsonNodeType.None; _dataType = JsonDataType.None; _isWritingDataTypeAttribute = false; _wroteServerTypeAttribute = false; _isWritingServerTypeAttribute = false; _serverTypeValue = null; _attributeText = null; if (_depth != 0) { _depth = 0; } if ((_scopes != null) && (_scopes.Length > JsonGlobals.maxScopeSize)) { _scopes = null; } // Can't let writeState be at Closed if reinitializing. _writeState = WriteState.Start; _endElementBuffer = false; _indentLevel = 0; }
/// <summary> /// Enter a new Scope /// Increase scopeDepth /// </summary> /// <param name="currentNodeType"></param> private void EnterJsonScope(JsonNodeType currentNodeType) { // Increase Depth ++scopeDepth; // Set the JsonNodeType of the current depth scopes[scopeDepth] = currentNodeType; }
public override void WriteEndElement() { if (IsClosed) { ThrowClosed(); } if (_depth == 0) { throw new XmlException(SR.JsonEndElementNoOpenNodes); } if (HasOpenAttribute) { throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteEndElement")); } _endElementBuffer = false; JsonNodeType token = ExitScope(); if (token == JsonNodeType.Collection) { _indentLevel--; if (_indent) { if (_nodeType == JsonNodeType.Element) { _nodeWriter.WriteText(WHITESPACE); } else { WriteNewLine(); WriteIndent(); } } _nodeWriter.WriteText(JsonGlobals.EndCollectionChar); token = ExitScope(); } else if (_nodeType == JsonNodeType.QuotedText) { // For writing " WriteJsonQuote(); } else if (_nodeType == JsonNodeType.Element) { if ((_dataType == JsonDataType.None) && (_serverTypeValue != null)) { throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString)); } if (IsWritingNameWithMapping && !WrittenNameWithMapping) { // Ending </item> without writing item attribute // Not providing a better error message because localization deadline has passed. throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.itemString, string.Empty, JsonGlobals.itemString)); } // the element is empty, it does not have any content, if ((_dataType == JsonDataType.None) || (_dataType == JsonDataType.String)) { _nodeWriter.WriteText(JsonGlobals.QuoteChar); _nodeWriter.WriteText(JsonGlobals.QuoteChar); } } else { // Assert on only StandaloneText and EndElement because preceding if // conditions take care of checking for QuotedText and Element. Fx.Assert((_nodeType == JsonNodeType.StandaloneText) || (_nodeType == JsonNodeType.EndElement), "nodeType has invalid value " + _nodeType + ". Expected it to be QuotedText, Element, StandaloneText, or EndElement."); } if (_depth != 0) { if (token == JsonNodeType.Element) { _endElementBuffer = true; } else if (token == JsonNodeType.Object) { _indentLevel--; if (_indent) { if (_nodeType == JsonNodeType.Element) { _nodeWriter.WriteText(WHITESPACE); } else { WriteNewLine(); WriteIndent(); } } _nodeWriter.WriteText(JsonGlobals.EndObjectChar); if ((_depth > 0) && _scopes[_depth] == JsonNodeType.Element) { ExitScope(); _endElementBuffer = true; } } } _dataType = JsonDataType.None; _nodeType = JsonNodeType.EndElement; _nameState = NameState.None; _wroteServerTypeAttribute = false; }
private void StartText() { if (HasOpenAttribute) throw new InvalidOperationException("JsonMustUseWriteStringForWritingAttributeValues"); if (dataType == JsonDataType.None && serverTypeValue != null) throw new XmlException("JsonMustSpecifyDataType"); if (IsWritingNameWithMapping && !WrittenNameWithMapping) throw new XmlException("JsonMustSpecifyDataType"); switch (dataType) { case JsonDataType.None: case JsonDataType.String: CheckText(JsonNodeType.QuotedText); if (nodeType != JsonNodeType.QuotedText) WriteJsonQuote(); nodeType = JsonNodeType.QuotedText; break; case JsonDataType.Boolean: case JsonDataType.Number: CheckText(JsonNodeType.StandaloneText); nodeType = JsonNodeType.StandaloneText; break; } }
private void CheckText(JsonNodeType nextNodeType) { if (IsClosed) ThrowClosed(); if (depth == 0) throw new InvalidOperationException("XmlIllegalOutsideRoot"); if (nextNodeType == JsonNodeType.StandaloneText && nodeType == JsonNodeType.QuotedText) throw new XmlException("JsonCannotWriteStandaloneTextAfterQuotedText"); }
private void InitializeWriter() { nodeType = JsonNodeType.None; dataType = JsonDataType.None; isWritingDataTypeAttribute = false; wroteServerTypeAttribute = false; isWritingServerTypeAttribute = false; serverTypeValue = null; attributeText = null; depth = 0; if (scopes != null && scopes.Length > 25) scopes = null; writeState = WriteState.Start; endElementBuffer = false; }
public override void WriteStartElement(string prefix, string localName, string ns) { if (localName == null) throw new ArgumentException("localName"); if (localName.Length == 0) throw new ArgumentException("localName", "JsonInvalidLocalNameEmpty"); if (!string.IsNullOrEmpty(prefix) && (string.IsNullOrEmpty(ns) || !TrySetWritingNameWithMapping(localName, ns))) throw new ArgumentException("prefix", "JsonPrefixMustBeNullOrEmpty"); if (!string.IsNullOrEmpty(ns) && !TrySetWritingNameWithMapping(localName, ns)) throw new ArgumentException("ns", "JsonNamespaceMustBeEmpty"); if (IsClosed) ThrowClosed(); if (HasOpenAttribute) throw new XmlException("JsonOpenAttributeMustBeClosedFirst"); if (nodeType != JsonNodeType.None && depth == 0) throw new XmlException("JsonMultipleRootElementsNotAllowedOnWriter"); switch (nodeType) { case JsonNodeType.None: if (!localName.Equals("root")) throw new XmlException("JsonInvalidRootElementName"); EnterScope(JsonNodeType.Element); break; case JsonNodeType.Element: if (dataType != JsonDataType.Array && dataType != JsonDataType.Object) throw new XmlException("JsonNodeTypeArrayOrObjectNotSpecified"); if (!IsWritingCollection) { if (nameState != NameState.IsWritingNameWithMapping) WriteJsonElementName(localName); } else if (!localName.Equals("item")) throw new XmlException("JsonInvalidItemNameForArrayElement"); EnterScope(JsonNodeType.Element); break; case JsonNodeType.EndElement: if (endElementBuffer) nodeWriter.Write(","); if (!IsWritingCollection) { if (nameState != NameState.IsWritingNameWithMapping) WriteJsonElementName(localName); } else if (!localName.Equals("item")) throw new XmlException("JsonInvalidItemNameForArrayElement"); EnterScope(JsonNodeType.Element); break; default: // ISSUE: reference to a compiler-generated method throw new XmlException("JsonInvalidStartElementCall"); } isWritingDataTypeAttribute = false; isWritingServerTypeAttribute = false; isWritingXmlnsAttribute = false; wroteServerTypeAttribute = false; serverTypeValue = null; dataType = JsonDataType.None; nodeType = JsonNodeType.Element; }
void InitializeWriter() { nodeType = JsonNodeType.None; dataType = JsonDataType.None; isWritingDataTypeAttribute = false; wroteServerTypeAttribute = false; isWritingServerTypeAttribute = false; serverTypeValue = null; attributeText = null; if (depth != 0) { depth = 0; } if ((scopes != null) && (scopes.Length > JsonGlobals.maxScopeSize)) { scopes = null; } // Can't let writeState be at Closed if reinitializing. writeState = WriteState.Start; endElementBuffer = false; indentLevel = 0; }
public override void WriteEndElement() { if (IsClosed) ThrowClosed(); if (depth == 0) throw new XmlException("JsonEndElementNoOpenNodes"); if (HasOpenAttribute) throw new XmlException("JsonOpenAttributeMustBeClosedFirst"); endElementBuffer = false; JsonNodeType jsonNodeType = ExitScope(); if (jsonNodeType == JsonNodeType.Collection) { //nodeWriter.WriteEndArray(); nodeWriter.Write("]"); jsonNodeType = ExitScope(); } else if (nodeType == JsonNodeType.QuotedText) WriteJsonQuote(); else if (nodeType == JsonNodeType.Element) { if (dataType == JsonDataType.None && serverTypeValue != null) throw new XmlException("JsonMustSpecifyDataType"); if (IsWritingNameWithMapping && !WrittenNameWithMapping) throw new XmlException("JsonMustSpecifyDataType"); if (dataType == JsonDataType.None || dataType == JsonDataType.String) { nodeWriter.Write(@""""); nodeWriter.Write(@""""); } } if (depth != 0) { if (jsonNodeType == JsonNodeType.Element) endElementBuffer = true; else if (jsonNodeType == JsonNodeType.Object) { nodeWriter.Write("}"); if (depth > 0 && scopes[depth] == JsonNodeType.Element) { ExitScope(); endElementBuffer = true; } } } dataType = JsonDataType.None; nodeType = JsonNodeType.EndElement; nameState = NameState.None; wroteServerTypeAttribute = false; }
private void EnterScope(JsonNodeType currentNodeType) { ++depth; if (scopes == null) scopes = new JsonNodeType[4]; else if (scopes.Length == depth) { var jsonNodeTypeArray = new JsonNodeType[depth * 2]; Array.Copy(scopes, jsonNodeTypeArray, depth); scopes = jsonNodeTypeArray; } scopes[depth] = currentNodeType; }
/// <summary> /// Called when end of input is reached. /// </summary> /// <returns>Always returns false, used for easy readability of the callers.</returns> private bool EndOfInput() { // We should be ending the input only with Root in the scope. if (this.scopes.Count > 1) { // Not all open scopes were closed. throw JsonReaderExtensions.CreateException(Strings.JsonReader_EndOfInputWithOpenScope); } Debug.Assert( this.scopes.Count > 0 && this.scopes.Peek().Type == ScopeType.Root && this.scopes.Peek().ValueCount <= 1, "The end of input should only occure with root at the top of the stack with zero or one value."); Debug.Assert(this.nodeValue == null, "The node value should have been reset to null."); this.nodeType = JsonNodeType.EndOfInput; return false; }
private void Consume(JsonNodeType openNodeType, JsonNodeType closeNodeType) { int nestLevel = 0; while (Read()) { if (NodeType == closeNodeType) { if (nestLevel == 0) { return; } nestLevel--; } else if (NodeType == openNodeType) { nestLevel++; } } }