public void ValueFormatting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue(null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteEndArray(); } string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,"""",""This is a string."",null,undefined]"; string result = sb.ToString(); Console.WriteLine("ValueFormatting"); Console.WriteLine(result); Assert.AreEqual(expected, result); }
public void JsonReaderToJsonWriter(JsonReader reader, JsonWriter writer) { do { switch (reader.TokenType) { case JsonToken.None: break; case JsonToken.StartObject: writer.WriteStartObject(); break; case JsonToken.StartArray: writer.WriteStartArray(); break; case JsonToken.PropertyName: string propertyName = reader.Value.ToString(); writer.WritePropertyName(ConvertPropertyName(propertyName)); break; case JsonToken.Comment: writer.WriteComment((reader.Value != null) ? reader.Value.ToString() : null); break; case JsonToken.Integer: writer.WriteValue(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture)); break; case JsonToken.Float: object value = reader.Value; if (value is decimal) { writer.WriteValue((decimal)value); } else if (value is double) { writer.WriteValue((double)value); } else if (value is float) { writer.WriteValue((float)value); } else { writer.WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture)); } break; case JsonToken.String: writer.WriteValue(reader.Value.ToString()); break; case JsonToken.Boolean: writer.WriteValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)); break; case JsonToken.Null: if (this.PropertyNullValueReplaceValue != null) { writer.WriteValue(this.PropertyNullValueReplaceValue); } else { writer.WriteNull(); } break; case JsonToken.Undefined: writer.WriteUndefined(); break; case JsonToken.EndObject: writer.WriteEndObject(); break; case JsonToken.EndArray: writer.WriteEndArray(); break; case JsonToken.EndConstructor: writer.WriteEndConstructor(); break; case JsonToken.Date: if (reader.Value is DateTimeOffset) { writer.WriteValue((DateTimeOffset)reader.Value); } else { writer.WriteValue(Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture)); } break; case JsonToken.Raw: writer.WriteRawValue((reader.Value != null) ? reader.Value.ToString() : null); break; case JsonToken.Bytes: if (reader.Value is Guid) { writer.WriteValue((Guid)reader.Value); } else { writer.WriteValue((byte[])reader.Value); } break; } } while (reader.Read()); }