public static JsonRecorder Record(JsonReader reader) { if (reader == null) throw new ArgumentNullException("reader"); JsonRecorder recorder = new JsonRecorder(); recorder.WriteFromReader(reader); return recorder; }
protected override object ImportFromString(Jayrock.Json.Conversion.ImportContext context, JsonReader reader) { try { string val = reader.ReadString().ToLower(); return (val == "1") || (val == "true") || (val == "t"); } catch (FormatException e) { throw new JsonException("Error importing JSON String as System.Boolean.", e); } }
protected override object ImportFromString(Jayrock.Json.Conversion.ImportContext context, JsonReader reader) { try { string val = reader.ReadString(); return DateTime.Parse(val); } catch (FormatException e) { throw new JsonException("Error importing JSON String as System.DateTime.", e); } }
/// <summary> /// The import. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="reader"> /// The reader. /// </param> /// <returns> /// The import. /// </returns> public object Import(ImportContext context, JsonReader reader) { // var properties = new EvolutionaryProperties(); // reader.StepOut(); // JsonToken token = reader.Token; this.properties = new EvolutionaryProperties(); PropertyValue[] o = context.Import<PropertyValue[]>(reader); this.SetProperties(o); return this.properties; }
public object Parse(JsonReader reader) { if (reader == null) throw new ArgumentNullException("reader"); // // Fault-in an AST strategy if one wasn't supplied thus far. // if (_output == null) _output = new ParserOutput(); return reader.DeserializeNext(_output); }
protected override void ImportElements(object collection, ImportContext context, JsonReader reader) { if (collection == null) throw new ArgumentNullException("collection"); if (context == null) throw new ArgumentNullException("context"); if (reader == null) throw new ArgumentNullException("reader"); object[] args = null; while (reader.TokenClass != JsonTokenClass.EndArray) { if (args == null) // on-demand args = new object[1]; args[0] = context.Import(ElementType, reader); InvokeAdd(collection, args); } }
protected override object ImportFromArray(ImportContext context, JsonReader reader) { if (context == null) throw new ArgumentNullException("context"); if (reader == null) throw new ArgumentNullException("reader"); object collection = CreateCollection(); reader.ReadToken(JsonTokenClass.Array); ImportElements(collection, context, reader); if (reader.TokenClass != JsonTokenClass.EndArray) throw new Exception("Implementation error."); reader.Read(); return collection; }
/// <remarks> /// This method is not exception-safe. If an error occurs while /// reading then the object may be partially imported. /// </remarks> public void Import(JsonReader reader) { Import(new ImportContext(), reader); }
void IJsonImportable.Import(ImportContext context, JsonReader reader) { Import(context, reader); }
public void WriteFromReader(JsonReader reader) { if (reader == null) throw new ArgumentNullException("reader"); while (!reader.EOF) WriteValueFromReader(reader); }
protected override object ImportFromString(Jayrock.Json.Conversion.ImportContext context, JsonReader reader) { try { string val = reader.ReadString(); int i = 0; foreach (string item in values) { if (item == val) return i; i++; } throw new JsonException("Error importing JSON String as " + this.OutputType.FullName + "."); } catch (FormatException e) { throw new JsonException("Error importing JSON String as " + this.OutputType.FullName + ".", e); } }
public static JsonBuffer From(JsonReader reader) { if (reader == null) throw new ArgumentNullException("reader"); JsonBufferReader bufferReader = reader as JsonBufferReader; if (bufferReader != null) return bufferReader.BufferValue(); if (!reader.MoveToContent()) return Empty; if (reader.TokenClass == JsonTokenClass.Member) reader.Read(); bool structured = reader.TokenClass == JsonTokenClass.Array || reader.TokenClass == JsonTokenClass.Object; JsonBufferWriter writer = new JsonBufferWriter(); writer.WriteFromReader(reader); JsonBuffer buffer = writer.GetBuffer(); if (!structured) { bufferReader = buffer.CreateReader(); bufferReader.MoveToContent(); bufferReader.Read(); buffer = bufferReader.BufferValue(); } return buffer; }
public void ImportJson(JsonReader reader) { ((IJsonImportable) this).Import(new ImportContext(), reader); }
/// <remarks> /// This method is not exception-safe. If an error occurs while /// reading then the object may be partially imported. /// </remarks> public virtual void Import(JsonReader reader) { if (reader == null) throw new ArgumentNullException("reader"); // FIXME: Consider making this method exception-safe. // Right now this is a problem because of reliance on // DictionaryBase. Clear(); reader.ReadToken(JsonTokenClass.Object); while (reader.TokenClass != JsonTokenClass.EndObject) Put(reader.ReadMember(), reader.ReadValue()); reader.Read(); }
public virtual void Process(JsonReader request, JsonWriter response) { if (request == null) throw new ArgumentNullException("request"); if (response == null) throw new ArgumentNullException("response"); IDictionary requestObject; try { requestObject = ParseRequest(request); } catch (BadRequestException e) { requestObject = e.Request as IDictionary; WriteResponse( CreateResponse(requestObject, /* result */ null, OnError(e.InnerException, requestObject)), response); return; } IDictionary responseObject = Invoke(requestObject); WriteResponse(responseObject, response); }
public object Import(Type type, JsonReader reader) { ImportCalled = true; return JsonConvert.Import(type, reader); }
protected abstract void ImportElements(object collection, ImportContext context, JsonReader reader);
protected override JsonToken ReadTokenImpl() { JsonReader baseReader = _reader; int index = _index; if (index < 0) { // // If the base reader was never started then do it now. // Check for zero depth is the same as BOF. // if (baseReader.Depth == 0) { baseReader.ReadToken(JsonTokenClass.Object); _innerDepth = baseReader.Depth; } _index = 0; return JsonToken.Object(); } // // Buffered members, if any, get served first. // NamedJsonBufferList bufferedMembers = _bufferedMembers; if (bufferedMembers != null && index < bufferedMembers.Count) { // // Is there a value to serve? // JsonBuffer value = _memberValue; if (!value.IsEmpty) { if (value.IsStructured) // JSON Array or Object { // // Get a reader on the structured (array or // object) value if not already acquired. // JsonReader valueReader = _memberStructuredValueReader; if (valueReader == null) valueReader = _memberStructuredValueReader = value.CreateReader(); // // Serve tokens from the value reader until OEF. // if (valueReader.Read()) return valueReader.Token; // // Proceed with next. // _memberValue = JsonBuffer.Empty; _memberStructuredValueReader = null; _index++; return ReadTokenImpl(); } else // JSON Null, Boolean, Number or String { Debug.Assert(value.IsNull || value.IsScalar); // // Establish state to proceed with next and // serve token pertaining to scalar value. // _memberValue = JsonBuffer.Empty; _index++; return value.IsNull ? JsonToken.Null() : value.CreateReader().Token; } } // // Serve buffered member name and establish state so // that the value will be served next. // NamedJsonBuffer member = (NamedJsonBuffer) bufferedMembers[index]; _memberValue = member.Buffer; return JsonToken.Member(member.Name); } // // Done with buffered members so now move on to remaining // members from the underlying reader. // if (baseReader == null) return JsonToken.EOF(); // Done with serving // // If base reader is on the object end at the same depth as // on entry then serve the last end token. The reader is // released so that on next read, the above will signal EOF. // if (baseReader.Depth == _innerDepth && baseReader.TokenClass == JsonTokenClass.EndObject) { _reader = null; } // // Move through the base reader. // JsonToken token = baseReader.Token; baseReader.Read(); return token; }
private object OnResponseArray(JsonReader reader, Type returnType) { Logger.Instance().Log("RPC", "Response"); var members = JsonBuffer.From(reader).GetArray();//.GetMembers();// .GetMembersArray(); foreach (var member in members) { var members2 = member.GetMembersArray();//JsonBuffer.From(member.).GetMembersArray(); foreach (var member2 in members2) { if (string.CompareOrdinal(member2.Name, "error") == 0) { var errorObject = JsonConvert.Import(member2.Buffer.CreateReader()); if (errorObject != null) OnError(errorObject); } else if (string.CompareOrdinal(member2.Name, "result") == 0) { Logger.Instance().Log("RPC", JsonConvert.Import(returnType, member2.Buffer.CreateReader()).ToString()); return returnType != typeof (JsonBuffer) ? JsonConvert.Import(returnType, member2.Buffer.CreateReader()) : member2.Buffer; } } } throw new JsonException("Invalid JSON-RPC response. It contains neither a result nor error."); }
void IJsonImportable.Import(ImportContext context, JsonReader reader) { reader.MoveToContent(); if (reader.TokenClass != JsonTokenClass.Object) { reader.Skip(); return; } reader.Read(/* object */); do { var brushName = reader.ReadMember().ToLowerInvariant(); var color = reader.ReadString(); var foreground = EnumHelper.TryParse<ConsoleColor>(color, true) ?? DefaultBrush.Foreground; switch (brushName) { case "arr": case "array": Array = Array.ResetForeground(foreground); break; case "obj": case "object": Object = Object.ResetForeground(foreground); break; case "mem": case "member": Member = Member.ResetForeground(foreground); break; case "str": case "string": String = String.ResetForeground(foreground); break; case "num": case "number": Number = Number.ResetForeground(foreground); break; case "bit": case "boolean": Boolean = Boolean.ResetForeground(foreground); break; case "nil": case "null": Null = Null.ResetForeground(foreground); break; default: continue; } } while (reader.TokenClass != JsonTokenClass.EndObject); reader.Read( /* end object */); }
/// <summary> /// Writes the next value from the given <see cref="JsonReader"/> /// into this writer's output. If the reader is positioned /// at the root of JSON data, then the entire data will be /// written. /// </summary> public virtual void WriteFromReader(JsonReader reader) { if (reader == null) throw new ArgumentNullException("reader"); if (!reader.MoveToContent()) return; if (reader.TokenClass == JsonTokenClass.String) { WriteString(reader.Text); } else if (reader.TokenClass == JsonTokenClass.Number) { WriteNumber(reader.Text); } else if (reader.TokenClass == JsonTokenClass.Boolean) { WriteBoolean(reader.Text == JsonBoolean.TrueText); } else if (reader.TokenClass == JsonTokenClass.Null) { WriteNull(); } else if (reader.TokenClass == JsonTokenClass.Array) { WriteStartArray(); reader.Read(); while (reader.TokenClass != JsonTokenClass.EndArray) WriteFromReader(reader); WriteEndArray(); } else if (reader.TokenClass == JsonTokenClass.Object) { reader.Read(); WriteStartObject(); while (reader.TokenClass != JsonTokenClass.EndObject) { WriteMember(reader.ReadMember()); WriteFromReader(reader); } WriteEndObject(); } else { throw new JsonException(string.Format("{0} not expected.", reader.TokenClass)); } reader.Read(); }
private int _index; // -1 = BOF; 0...(N-1) = buffered members; N = streamed members public TailReader(JsonReader reader, NamedJsonBufferList bufferedMembers) { Debug.Assert(reader != null); _reader = reader; _innerDepth = reader.Depth; _bufferedMembers = bufferedMembers; _index = -1; }
public override object Import(Type type, JsonReader reader) { ImportCalled = true; return base.Import(type, reader); }
protected virtual void Import(ImportContext context, JsonReader reader) { if (context == null) throw new ArgumentNullException("context"); if (reader == null) throw new ArgumentNullException("reader"); // // IMPORTANT! A new list is created and then committed to make // sure that this method is exception-safe. If something goes // wrong during the import of elements then this instance // will remain largely untouched. // ArrayList list = new ArrayList(); reader.ReadToken(JsonTokenClass.Array); while (reader.TokenClass != JsonTokenClass.EndArray) list.Add(context.Import(reader)); reader.Read(); InnerList.Clear(); InnerList.AddRange(list); }
protected virtual IDictionary ParseRequest(JsonReader input) { if (input == null) throw new ArgumentNullException("input"); JsonReader reader = input; // alias for clarity JsonImportHandler importer = JsonImporter; JsonObject request = new JsonObject(); Method method = null; JsonReader paramsReader = null; object args = null; try { reader.ReadToken(JsonTokenClass.Object); while (reader.TokenClass != JsonTokenClass.EndObject) { string memberName = reader.ReadMember(); switch (memberName) { case "id" : { request["id"] = importer(AnyType.Value, reader); break; } case "method" : { string methodName = reader.ReadString(); request["method"] = methodName; method = Service.GetClass().GetMethodByName(methodName); if (paramsReader != null) { // // If the parameters were already read in and // buffer, then deserialize them now that we know // the method we're dealing with. // args = ReadParameters(method, paramsReader, importer); paramsReader = null; } break; } case "params" : { // // Is the method already known? If so, then we can // deserialize the parameters right away. Otherwise // we record them until hopefully the method is // encountered. // if (method != null) { args = ReadParameters(method, reader, importer); } else { JsonRecorder recorder = new JsonRecorder(); recorder.WriteFromReader(reader); paramsReader = recorder.CreatePlayer(); } break; } default: { reader.Skip(); break; } } } reader.Read(); if (args != null) request["params"] = args; return request; } catch (JsonException e) { throw new BadRequestException(e.Message, e, request); } catch (MethodNotFoundException e) { throw new BadRequestException(e.Message, e, request); } }
public object OnResponse(JsonReader reader, Type returnType) { Debug.Assert(reader != null); Debug.Assert(returnType != null); bool resultSpecified = false; object result = null; // // JSON-RPC 2.0 specification/protocol, states that either error // or result must be present but not both. JSON-RPC 1.0 is less // strict and states that one or the other must be null. There // is an ambiguity however with 1.0 when both result and error // are null. Here, it is treated like a successful null result. // NamedJsonBuffer[] members = JsonBuffer.From(reader).GetMembersArray(); foreach (NamedJsonBuffer member in members) { if (string.CompareOrdinal(member.Name, "error") == 0) { object errorObject = JsonConvert.Import(member.Buffer.CreateReader()); if (errorObject != null) OnError(errorObject); } else if (string.CompareOrdinal(member.Name, "result") == 0) { resultSpecified = true; result = returnType != typeof(JsonBuffer) ? JsonConvert.Import(returnType, member.Buffer.CreateReader()) : member.Buffer; } } if (!resultSpecified) // never gets here on error throw new Exception("Invalid JSON-RPC response. It contains neither a result nor an error."); return result; }
private object OnResponse(JsonReader reader, Type returnType) { Debug.Assert(reader != null); Debug.Assert(returnType != null); NamedJsonBuffer[] members = JsonBuffer.From(reader).GetMembersArray(); foreach (NamedJsonBuffer member in members) { if (string.CompareOrdinal(member.Name, "error") == 0) { object errorObject = JsonConvert.Import(member.Buffer.CreateReader()); if (errorObject != null) OnError(errorObject); } else if (string.CompareOrdinal(member.Name, "result") == 0) { return returnType != typeof(JsonBuffer) ? JsonConvert.Import(returnType, member.Buffer.CreateReader()) : member.Buffer; } } throw new Exception("Invalid JSON-RPC response. It contains neither a result nor an error."); }
private NamedJsonBufferList _members; // buffered ones public FreeJsonMemberReadingHelper(JsonReader reader) { if (reader == null) throw new ArgumentNullException("reader"); JsonTokenClass clazz = reader.TokenClass; if (clazz != JsonTokenClass.BOF && clazz != JsonTokenClass.Object && clazz != JsonTokenClass.Member) { throw new ArgumentException(null, "reader"); } _reader = reader; }
private static object ReadParameters(Method method, JsonReader reader, ImportContext importContext) { Debug.Assert(method != null); Debug.Assert(reader != null); Debug.Assert(importContext != null); reader.MoveToContent(); Parameter[] parameters = method.GetParameters(); if (reader.TokenClass == JsonTokenClass.Array) { reader.Read(); ArrayList argList = new ArrayList(parameters.Length); // TODO: This loop could bomb when more args are supplied that parameters available. for (int i = 0; i < parameters.Length && reader.TokenClass != JsonTokenClass.EndArray; i++) argList.Add(importContext.Import(parameters[i].ParameterType, reader)); reader.StepOut(); return argList.ToArray(); } else if (reader.TokenClass == JsonTokenClass.Object) { reader.Read(); JsonObject argByName = new JsonObject(); while (reader.TokenClass != JsonTokenClass.EndObject) { // TODO: Imporve this lookup. // FIXME: Does not work when argument is positional. Type parameterType = AnyType.Value; string name = reader.ReadMember(); foreach (Parameter parameter in parameters) { if (parameter.Name.Equals(name)) { parameterType = parameter.ParameterType; break; } } argByName.Put(name, importContext.Import(parameterType, reader)); } reader.Read(); return argByName; } else { return importContext.Import(reader); } }
public virtual void Import(JsonReader reader) { Import(JsonConvert.CreateImportContext(), reader); }