Esempio n. 1
0
        public void DeserializePublicExtensionData()
        {
            string json = @"{
  'Name':'Name!',
  'NoMatch':'NoMatch!',
  'ExtensionData':{'HAI':true}
}";

            var c = JsonConvert.DeserializeObject <PublicExtensionDataAttributeTestClass>(json);

            Assert.AreEqual("Name!", c.Name);
            Assert.AreEqual(2, c.ExtensionData.Count);

            Assert.AreEqual("NoMatch!", (string)c.ExtensionData["NoMatch"]);

            // the ExtensionData property is put into the extension data
            // inception
            var o = (JObject)c.ExtensionData["ExtensionData"];

            Assert.AreEqual(1, o.Count);
            Assert.IsTrue(JToken.DeepEquals(new JObject {
                { "HAI", true }
            }, o));
        }
        public void UnusedFailingDependencySchema_InsideAllOf()
        {
            JSchema schema = JSchema.Parse(@"{
                ""dependencies"": {
                    ""bar"": {
                        ""properties"": {
                            ""foo"": {""type"": ""integer""},
                            ""bar"": {""type"": ""integer""}
                        }
                    }
                }
            }");

            JSchema root = new JSchema();

            root.AllOf.Add(schema);

            JToken json = JToken.Parse(@"{""foo"":""quux""}");

            IList <ValidationError> errors;
            bool isValid = json.IsValid(root, out errors);

            Assert.IsTrue(isValid);
        }
Esempio n. 3
0
        public void WriteByteArray()
        {
            MemoryStream ms     = new MemoryStream();
            BsonWriter   writer = new BsonWriter(ms);

            writer.WriteStartObject();
            writer.WritePropertyName("array0");
            writer.WriteValue(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 });
            writer.WritePropertyName("array1");
            writer.WriteValue(default(byte[]));
            writer.WriteEndObject();
            ms.Seek(0, SeekOrigin.Begin);

            BsonReader reader = new BsonReader(ms);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
            Assert.AreEqual(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }, reader.ReadAsBytes());
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
            Assert.IsNull(reader.ReadAsBytes());
        }
Esempio n. 4
0
        public void WriteUri()
        {
            MemoryStream ms     = new MemoryStream();
            BsonWriter   writer = new BsonWriter(ms);

            writer.WriteStartObject();
            writer.WritePropertyName("uri0");
            writer.WriteValue(new Uri("http://example.net/"));
            writer.WritePropertyName("uri1");
            writer.WriteValue(default(Uri));
            writer.WriteEndObject();
            ms.Seek(0, SeekOrigin.Begin);

            BsonReader reader = new BsonReader(ms);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
            Assert.AreEqual("http://example.net/", reader.ReadAsString());
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
            Assert.IsNull(reader.ReadAsString());
        }
        public void ReferencedObjectItems()
        {
            ReferenceObject o1 = new ReferenceObject();

            o1.Component1 = new TestComponentSimple {
                MyProperty = 1
            };
            o1.Component2            = o1.Component1;
            o1.ComponentNotReference = new TestComponentSimple();
            o1.String  = "String!";
            o1.Integer = int.MaxValue;

            string json     = JsonConvert.SerializeObject(o1, Formatting.Indented);
            string expected = @"{
  ""Component1"": {
    ""$id"": ""1"",
    ""MyProperty"": 1
  },
  ""Component2"": {
    ""$ref"": ""1""
  },
  ""ComponentNotReference"": {
    ""MyProperty"": 0
  },
  ""String"": ""String!"",
  ""Integer"": 2147483647
}";

            StringAssert.AreEqual(expected, json);

            ReferenceObject referenceObject = JsonConvert.DeserializeObject <ReferenceObject>(json);

            Assert.IsNotNull(referenceObject);

            Assert.IsTrue(ReferenceEquals(referenceObject.Component1, referenceObject.Component2));
        }
Esempio n. 6
0
        public void ReadStringValue_Numbers_NotString()
        {
            JsonTextReader reader = new JsonTextReader(new StringReader("[56,56]"));

            reader.Read();

            ExceptionAssert.Throws <JsonReaderException>(() =>
            {
                reader.ReadAsDateTime();
            }, "Unexpected character encountered while parsing value: 5. Path '', line 1, position 2.");

            ExceptionAssert.Throws <JsonReaderException>(() =>
            {
                reader.ReadAsDateTime();
            }, "Unexpected character encountered while parsing value: 6. Path '', line 1, position 3.");

            ExceptionAssert.Throws <JsonReaderException>(() =>
            {
                reader.ReadAsDateTime();
            }, "Unexpected character encountered while parsing value: ,. Path '[0]', line 1, position 4.");

            Assert.AreEqual(56, reader.ReadAsInt32());
            Assert.IsTrue(reader.Read());
        }
Esempio n. 7
0
 public void JValueIConvertable()
 {
     Assert.IsTrue(new JValue(0) is IConvertible);
 }
Esempio n. 8
0
        public void YahooFinance()
        {
            JObject o =
                new JObject(
                    new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)),
                    new JProperty("Test2", new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0))),
                    new JProperty("Test3", "Test3Value"),
                    new JProperty("Test4", null)
                    );

            using (JTokenReader jsonReader = new JTokenReader(o))
            {
                IJsonLineInfo lineInfo = jsonReader;

                jsonReader.Read();
                Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);
                Assert.AreEqual(false, lineInfo.HasLineInfo());

                jsonReader.Read();
                Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
                Assert.AreEqual("Test1", jsonReader.Value);
                Assert.AreEqual(false, lineInfo.HasLineInfo());

                jsonReader.Read();
                Assert.AreEqual(JsonToken.Date, jsonReader.TokenType);
                Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), jsonReader.Value);
                Assert.AreEqual(false, lineInfo.HasLineInfo());
                Assert.AreEqual(0, lineInfo.LinePosition);
                Assert.AreEqual(0, lineInfo.LineNumber);

                jsonReader.Read();
                Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
                Assert.AreEqual("Test2", jsonReader.Value);

                jsonReader.Read();
                Assert.AreEqual(JsonToken.Date, jsonReader.TokenType);
                Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value);

                jsonReader.Read();
                Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
                Assert.AreEqual("Test3", jsonReader.Value);

                jsonReader.Read();
                Assert.AreEqual(JsonToken.String, jsonReader.TokenType);
                Assert.AreEqual("Test3Value", jsonReader.Value);

                jsonReader.Read();
                Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
                Assert.AreEqual("Test4", jsonReader.Value);

                jsonReader.Read();
                Assert.AreEqual(JsonToken.Null, jsonReader.TokenType);
                Assert.AreEqual(null, jsonReader.Value);

                Assert.IsTrue(jsonReader.Read());
                Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType);

                Assert.IsFalse(jsonReader.Read());
                Assert.AreEqual(JsonToken.None, jsonReader.TokenType);
            }

            using (JsonReader jsonReader = new JTokenReader(o.Property("Test2")))
            {
                Assert.IsTrue(jsonReader.Read());
                Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
                Assert.AreEqual("Test2", jsonReader.Value);

                Assert.IsTrue(jsonReader.Read());
                Assert.AreEqual(JsonToken.Date, jsonReader.TokenType);
                Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value);

                Assert.IsFalse(jsonReader.Read());
                Assert.AreEqual(JsonToken.None, jsonReader.TokenType);
            }
        }
Esempio n. 9
0
        public void SpecifiedTest()
        {
            SpecifiedTestClass c = new SpecifiedTestClass();

            c.Name          = "James";
            c.Age           = 27;
            c.NameSpecified = false;

            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
            {
                LevelFilter = TraceLevel.Verbose
            };

            string json = JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings {
                TraceWriter = traceWriter
            });

            Assert.AreEqual("Started serializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path ''.", traceWriter.TraceRecords[0].Message);
            Assert.AreEqual("IsSpecified result for property 'Name' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass: False. Path ''.", traceWriter.TraceRecords[1].Message);
            Assert.AreEqual("IsSpecified result for property 'Weight' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass: False. Path 'Age'.", traceWriter.TraceRecords[2].Message);
            Assert.AreEqual("IsSpecified result for property 'Height' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass: False. Path 'Age'.", traceWriter.TraceRecords[3].Message);
            Assert.AreEqual("IsSpecified result for property 'FavoriteNumber' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass: False. Path 'Age'.", traceWriter.TraceRecords[4].Message);
            Assert.AreEqual("Finished serializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path ''.", traceWriter.TraceRecords[5].Message);

            StringAssert.AreEqual(@"{
  ""Age"": 27
}", json);

            traceWriter = new InMemoryTraceWriter
            {
                LevelFilter = TraceLevel.Verbose
            };

            SpecifiedTestClass deserialized = JsonConvert.DeserializeObject <SpecifiedTestClass>(json, new JsonSerializerSettings {
                TraceWriter = traceWriter
            });

            Assert.AreEqual("Started deserializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path 'Age', line 2, position 9.", traceWriter.TraceRecords[0].Message);
            Assert.IsTrue(traceWriter.TraceRecords[1].Message.StartsWith("Finished deserializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path ''"));

            Assert.IsNull(deserialized.Name);
            Assert.IsFalse(deserialized.NameSpecified);
            Assert.IsFalse(deserialized.WeightSpecified);
            Assert.IsFalse(deserialized.HeightSpecified);
            Assert.IsFalse(deserialized.FavoriteNumberSpecified);
            Assert.AreEqual(27, deserialized.Age);

            c.NameSpecified   = true;
            c.WeightSpecified = true;
            c.HeightSpecified = true;
            c.FavoriteNumber  = 23;
            json = JsonConvert.SerializeObject(c, Formatting.Indented);

            StringAssert.AreEqual(@"{
  ""Name"": ""James"",
  ""Age"": 27,
  ""Weight"": 0,
  ""Height"": 0,
  ""FavoriteNumber"": 23
}", json);

            traceWriter = new InMemoryTraceWriter
            {
                LevelFilter = TraceLevel.Verbose
            };

            deserialized = JsonConvert.DeserializeObject <SpecifiedTestClass>(json, new JsonSerializerSettings {
                TraceWriter = traceWriter
            });

            Assert.AreEqual("Started deserializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path 'Name', line 2, position 10.", traceWriter.TraceRecords[0].Message);
            Assert.AreEqual("IsSpecified for property 'Name' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass set to true. Path 'Name', line 2, position 18.", traceWriter.TraceRecords[1].Message);
            Assert.AreEqual("IsSpecified for property 'Weight' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass set to true. Path 'Weight', line 4, position 14.", traceWriter.TraceRecords[2].Message);
            Assert.AreEqual("IsSpecified for property 'Height' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass set to true. Path 'Height', line 5, position 14.", traceWriter.TraceRecords[3].Message);
            Assert.IsTrue(traceWriter.TraceRecords[4].Message.StartsWith("Finished deserializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path ''"));

            Assert.AreEqual("James", deserialized.Name);
            Assert.IsTrue(deserialized.NameSpecified);
            Assert.IsTrue(deserialized.WeightSpecified);
            Assert.IsTrue(deserialized.HeightSpecified);
            Assert.IsTrue(deserialized.FavoriteNumberSpecified);
            Assert.AreEqual(27, deserialized.Age);
            Assert.AreEqual(23, deserialized.FavoriteNumber);
        }
Esempio n. 10
0
        public void SingleLineComments()
        {
            string json = @"//comment*//*hi*/
{//comment
Name://comment
true//comment after true" + StringUtils.CarriageReturn +
                          @",//comment after comma" + StringUtils.CarriageReturnLineFeed +
                          @"""ExpiryDate""://comment" + StringUtils.LineFeed +
                          @"new " + StringUtils.LineFeed +
                          @"Date
(//comment
null//comment
),
        ""Price"": 3.99,
        ""Sizes"": //comment
[//comment

          ""Small""//comment
]//comment
}//comment 
//comment 1 ";

            JsonTextReader reader = new JsonTextReader(new StreamReader(new SlowStream(json, new UTF8Encoding(false), 1)));

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);
            Assert.AreEqual("comment*//*hi*/", reader.Value);
            Assert.AreEqual(1, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(2, reader.LineNumber);
            Assert.AreEqual(JsonToken.StartObject, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);
            Assert.AreEqual(2, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
            Assert.AreEqual("Name", reader.Value);
            Assert.AreEqual(3, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);
            Assert.AreEqual(3, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Boolean, reader.TokenType);
            Assert.AreEqual(true, reader.Value);
            Assert.AreEqual(4, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);
            Assert.AreEqual("comment after true", reader.Value);
            Assert.AreEqual(4, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);
            Assert.AreEqual("comment after comma", reader.Value);
            Assert.AreEqual(5, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
            Assert.AreEqual("ExpiryDate", reader.Value);
            Assert.AreEqual(6, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);
            Assert.AreEqual(6, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartConstructor, reader.TokenType);
            Assert.AreEqual(9, reader.LineNumber);
            Assert.AreEqual("Date", reader.Value);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Null, reader.TokenType);
            Assert.AreEqual(10, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);
            Assert.AreEqual(10, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndConstructor, reader.TokenType);
            Assert.AreEqual(11, reader.LineNumber);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
            Assert.AreEqual("Price", reader.Value);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Float, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
            Assert.AreEqual("Sizes", reader.Value);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartArray, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.String, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndArray, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndObject, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);
            Assert.AreEqual("comment ", reader.Value);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Comment, reader.TokenType);
            Assert.AreEqual("comment 1 ", reader.Value);

            Assert.IsFalse(reader.Read());
        }
Esempio n. 11
0
        public void LineInfoAndNewLines()
        {
            string json = "{}";

            JsonTextReader jsonTextReader = new JsonTextReader(new StringReader(json));

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.StartObject, jsonTextReader.TokenType);
            Assert.AreEqual(1, jsonTextReader.LineNumber);
            Assert.AreEqual(1, jsonTextReader.LinePosition);

            Assert.IsTrue(jsonTextReader.Read());

            Assert.AreEqual(JsonToken.EndObject, jsonTextReader.TokenType);
            Assert.AreEqual(1, jsonTextReader.LineNumber);
            Assert.AreEqual(2, jsonTextReader.LinePosition);

            json = "\n{\"a\":\"bc\"}";

            jsonTextReader = new JsonTextReader(new StringReader(json));

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.StartObject, jsonTextReader.TokenType);
            Assert.AreEqual(2, jsonTextReader.LineNumber);
            Assert.AreEqual(1, jsonTextReader.LinePosition);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.PropertyName, jsonTextReader.TokenType);
            Assert.AreEqual(2, jsonTextReader.LineNumber);
            Assert.AreEqual(5, jsonTextReader.LinePosition);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.String, jsonTextReader.TokenType);
            Assert.AreEqual(2, jsonTextReader.LineNumber);
            Assert.AreEqual(9, jsonTextReader.LinePosition);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.EndObject, jsonTextReader.TokenType);
            Assert.AreEqual(2, jsonTextReader.LineNumber);
            Assert.AreEqual(10, jsonTextReader.LinePosition);

            json = "\n{\"a\":\n\"bc\",\"d\":true\n}";

            jsonTextReader = new JsonTextReader(new StringReader(json));

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.StartObject, jsonTextReader.TokenType);
            Assert.AreEqual(2, jsonTextReader.LineNumber);
            Assert.AreEqual(1, jsonTextReader.LinePosition);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.PropertyName, jsonTextReader.TokenType);
            Assert.AreEqual(2, jsonTextReader.LineNumber);
            Assert.AreEqual(5, jsonTextReader.LinePosition);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.String, jsonTextReader.TokenType);
            Assert.AreEqual(3, jsonTextReader.LineNumber);
            Assert.AreEqual(4, jsonTextReader.LinePosition);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.PropertyName, jsonTextReader.TokenType);
            Assert.AreEqual(3, jsonTextReader.LineNumber);
            Assert.AreEqual(9, jsonTextReader.LinePosition);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.Boolean, jsonTextReader.TokenType);
            Assert.AreEqual(3, jsonTextReader.LineNumber);
            Assert.AreEqual(13, jsonTextReader.LinePosition);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.EndObject, jsonTextReader.TokenType);
            Assert.AreEqual(4, jsonTextReader.LineNumber);
            Assert.AreEqual(1, jsonTextReader.LinePosition);
        }
Esempio n. 12
0
 public void DeepEquals()
 {
     Assert.IsTrue(JToken.DeepEquals(new JValue(5L), new JValue(5)));
     Assert.IsFalse(JToken.DeepEquals(new JValue(5M), new JValue(5)));
     Assert.IsTrue(JToken.DeepEquals(new JValue((ulong)long.MaxValue), new JValue(long.MaxValue)));
 }
        public void TV4_Issue_86()
        {
            string schemaJson = @"{
			""type"": ""object"",
			""properties"": {
				""shape"": {
					""oneOf"": [
						{ ""$ref"": ""#/definitions/squareSchema"" },
						{ ""$ref"": ""#/definitions/circleSchema"" }
					]
				}
			},
			""definitions"": {
				""squareSchema"": {
					""type"": ""object"",
					""properties"": {
						""thetype"": {
							""type"": ""string"",
							""enum"": [""square""]
						},
						""colour"": {},
						""shade"": {},
						""boxname"": {
							""type"": ""string""
						}
					},
					""oneOf"": [
						{ ""$ref"": ""#/definitions/colourSchema"" },
						{ ""$ref"": ""#/definitions/shadeSchema"" }
					],
					""required"": [""thetype"", ""boxname""],
					""additionalProperties"": false
				},
				""circleSchema"": {
					""type"": ""object"",
					""properties"": {
						""thetype"": {
							""type"": ""string"",
							""enum"": [""circle""]
						},
						""colour"": {},
						""shade"": {}
					},
					""oneOf"": [
						{ ""$ref"": ""#/definitions/colourSchema"" },
						{ ""$ref"": ""#/definitions/shadeSchema"" }
					],
					""additionalProperties"": false
				},
				""colourSchema"": {
					""type"": ""object"",
					""properties"": {
						""colour"": {
							""type"": ""string""
						},
						""shade"": {
							""type"": ""null""
						}
					}
				},
				""shadeSchema"": {
					""type"": ""object"",
					""properties"": {
						""shade"": {
							""type"": ""string""
						},
						""colour"": {
							""type"": ""null""
						}
					}
				}
			}
		}"        ;

            JObject o = JObject.Parse(@"{
			""shape"": {
				""thetype"": ""circle"",
				""shade"": ""red""
			}
		}"        );

            JSchema schema = JSchema.Parse(schemaJson);

            bool isValid = o.IsValid(schema);

            Assert.IsTrue(isValid);
        }
Esempio n. 14
0
        public async Task ParseDoublesAsync()
        {
            JsonTextReader reader = new JsonTextReader(new StringReader("1.1"));

            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(1.1d, reader.Value);

            reader = new JsonTextReader(new StringReader("-1.1"));
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(-1.1d, reader.Value);

            reader = new JsonTextReader(new StringReader("0.0"));
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(0.0d, reader.Value);

            reader = new JsonTextReader(new StringReader("-0.0"));
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(-0.0d, reader.Value);

            reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd"));
            await ExceptionAssert.ThrowsAsync <JsonReaderException>(async() => await reader.ReadAsync(), "Unexpected character encountered while parsing number: s. Path '', line 1, position 77.");

            reader = new JsonTextReader(new StringReader("1E-06"));
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(0.000001d, reader.Value);

            reader = new JsonTextReader(new StringReader(""));
            Assert.IsFalse(await reader.ReadAsync());

            reader = new JsonTextReader(new StringReader("-"));
            await ExceptionAssert.ThrowsAsync <JsonReaderException>(async() => await reader.ReadAsync(), "Input string '-' is not a valid number. Path '', line 1, position 1.");

            reader = new JsonTextReader(new StringReader("1.7976931348623157E+308"));
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(Double.MaxValue, reader.Value);

            reader = new JsonTextReader(new StringReader("-1.7976931348623157E+308"));
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(Double.MinValue, reader.Value);

            reader = new JsonTextReader(new StringReader("1E+309"));
#if !(NETSTANDARD2_0 || NETSTANDARD1_3)
            await ExceptionAssert.ThrowsAsync <JsonReaderException>(async() => await reader.ReadAsync(), "Input string '1E+309' is not a valid number. Path '', line 1, position 6.");
#else
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(Double.PositiveInfinity, reader.Value);
#endif

            reader = new JsonTextReader(new StringReader("-1E+5000"));
#if !(NETSTANDARD2_0 || NETSTANDARD1_3)
            await ExceptionAssert.ThrowsAsync <JsonReaderException>(async() => await reader.ReadAsync(), "Input string '-1E+5000' is not a valid number. Path '', line 1, position 8.");
#else
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(Double.NegativeInfinity, reader.Value);
#endif

            reader = new JsonTextReader(new StringReader("5.1231231E"));
            await ExceptionAssert.ThrowsAsync <JsonReaderException>(async() => await reader.ReadAsync(), "Input string '5.1231231E' is not a valid number. Path '', line 1, position 10.");

            reader = new JsonTextReader(new StringReader("1E-23"));
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(1e-23, reader.Value);
        }
Esempio n. 15
0
        public async Task ReadFromAsync()
        {
            JObject o = (JObject)await JToken.ReadFromAsync(
                new JsonTextReader(new StringReader("{'pie':true}"))
                );

            Assert.AreEqual(true, (bool)o["pie"]);

            JArray a = (JArray)await JToken.ReadFromAsync(
                new JsonTextReader(new StringReader("[1,2,3]"))
                );

            Assert.AreEqual(1, (int)a[0]);
            Assert.AreEqual(2, (int)a[1]);
            Assert.AreEqual(3, (int)a[2]);

            JsonReader reader = new JsonTextReader(new StringReader("{'pie':true}"));
            await reader.ReadAsync();

            await reader.ReadAsync();

            JProperty p = (JProperty)await JToken.ReadFromAsync(reader);

            Assert.AreEqual("pie", p.Name);
            Assert.AreEqual(true, (bool)p.Value);

            JConstructor c = (JConstructor)await JToken.ReadFromAsync(
                new JsonTextReader(new StringReader("new Date(1)"))
                );

            Assert.AreEqual("Date", c.Name);
            Assert.IsTrue(JToken.DeepEquals(new JValue(1), c.Values().ElementAt(0)));

            JValue v = (JValue)await JToken.ReadFromAsync(
                new JsonTextReader(new StringReader(@"""stringvalue"""))
                );

            Assert.AreEqual("stringvalue", (string)v);

            v = (JValue)await JToken.ReadFromAsync(new JsonTextReader(new StringReader(@"1")));

            Assert.AreEqual(1, (int)v);

            v = (JValue)await JToken.ReadFromAsync(new JsonTextReader(new StringReader(@"1.1")));

            Assert.AreEqual(1.1, (double)v);

            v = (JValue)await JToken.ReadFromAsync(
                new JsonTextReader(new StringReader(@"""1970-01-01T00:00:00+12:31"""))
            {
                DateParseHandling = DateParseHandling.DateTimeOffset
            }
                );

            Assert.AreEqual(typeof(DateTimeOffset), v.Value.GetType());
            Assert.AreEqual(
                new DateTimeOffset(
                    DateTimeUtils.InitialJavaScriptDateTicks,
                    new TimeSpan(12, 31, 0)
                    ),
                v.Value
                );
        }
Esempio n. 16
0
        public void ImplicitCastingTo()
        {
            Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTime(2000, 12, 20)), (JValue) new DateTime(2000, 12, 20)));
#if !NET20
            Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)), (JValue) new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
            Assert.IsTrue(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null));
#endif

#if !(NET20 || NET35 || PORTABLE || ASPNETCORE50 || PORTABLE40)
            // had to remove implicit casting to avoid user reference to System.Numerics.dll
            Assert.IsTrue(JToken.DeepEquals(new JValue(new BigInteger(1)), new JValue(new BigInteger(1))));
            Assert.IsTrue(JToken.DeepEquals(new JValue((BigInteger?)null), new JValue((BigInteger?)null)));
#endif
            Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true));
            Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true));
            Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)(bool?)true));
            Assert.IsTrue(JToken.DeepEquals(new JValue((bool?)null), (JValue)(bool?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue(10), (JValue)10));
            Assert.IsTrue(JToken.DeepEquals(new JValue((long?)null), (JValue)(long?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue(long.MaxValue), (JValue)long.MaxValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue((int?)null), (JValue)(int?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue((short?)null), (JValue)(short?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue((double?)null), (JValue)(double?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue((uint?)null), (JValue)(uint?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue((decimal?)null), (JValue)(decimal?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue((ulong?)null), (JValue)(ulong?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte?)null), (JValue)(sbyte?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte)1), (JValue)(sbyte)1));
            Assert.IsTrue(JToken.DeepEquals(new JValue((byte?)null), (JValue)(byte?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue((byte)1), (JValue)(byte)1));
            Assert.IsTrue(JToken.DeepEquals(new JValue((ushort?)null), (JValue)(ushort?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue(short.MaxValue), (JValue)short.MaxValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue(ushort.MaxValue), (JValue)ushort.MaxValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue(11.1f), (JValue)11.1f));
            Assert.IsTrue(JToken.DeepEquals(new JValue(float.MinValue), (JValue)float.MinValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue(double.MinValue), (JValue)double.MinValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue(uint.MaxValue), (JValue)uint.MaxValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MaxValue), (JValue)ulong.MaxValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MinValue), (JValue)ulong.MinValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue((string)null), (JValue)(string)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)decimal.MaxValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)(decimal?)decimal.MaxValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MinValue), (JValue)decimal.MinValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue(float.MaxValue), (JValue)(float?)float.MaxValue));
            Assert.IsTrue(JToken.DeepEquals(new JValue(double.MaxValue), (JValue)(double?)double.MaxValue));
            Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(double?)null));

            Assert.IsFalse(JToken.DeepEquals(new JValue(true), (JValue)(bool?)null));
            Assert.IsFalse(JToken.DeepEquals(JValue.CreateNull(), (JValue)(object)null));

            byte[] emptyData = new byte[0];
            Assert.IsTrue(JToken.DeepEquals(new JValue(emptyData), (JValue)emptyData));
            Assert.IsFalse(JToken.DeepEquals(new JValue(emptyData), (JValue) new byte[1]));
            Assert.IsTrue(JToken.DeepEquals(new JValue(Encoding.UTF8.GetBytes("Hi")), (JValue)Encoding.UTF8.GetBytes("Hi")));

            Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)TimeSpan.FromMinutes(1)));
            Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(TimeSpan?)null));
            Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)(TimeSpan?)TimeSpan.FromMinutes(1)));
            Assert.IsTrue(JToken.DeepEquals(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")), (JValue) new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")));
            Assert.IsTrue(JToken.DeepEquals(new JValue(new Uri("http://www.google.com")), (JValue) new Uri("http://www.google.com")));
            Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Uri)null));
            Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Guid?)null));
        }
Esempio n. 17
0
        public void CalculatingPropertyNameEscapedSkipping()
        {
            JsonProperty p = new JsonProperty {
                PropertyName = "abc"
            };

            Assert.IsTrue(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "123"
            };
            Assert.IsTrue(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "._-"
            };
            Assert.IsTrue(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "!@#"
            };
            Assert.IsTrue(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "$%^"
            };
            Assert.IsTrue(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "?*("
            };
            Assert.IsTrue(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = ")_+"
            };
            Assert.IsTrue(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "=:,"
            };
            Assert.IsTrue(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = null
            };
            Assert.IsTrue(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "&"
            };
            Assert.IsFalse(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "<"
            };
            Assert.IsFalse(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = ">"
            };
            Assert.IsFalse(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "'"
            };
            Assert.IsFalse(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = @""""
            };
            Assert.IsFalse(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = Environment.NewLine
            };
            Assert.IsFalse(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "\0"
            };
            Assert.IsFalse(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "\n"
            };
            Assert.IsFalse(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "\v"
            };
            Assert.IsFalse(p._skipPropertyNameEscape);

            p = new JsonProperty {
                PropertyName = "\u00B9"
            };
            Assert.IsFalse(p._skipPropertyNameEscape);
        }
Esempio n. 18
0
        public async Task DateParseHandlingAsync()
        {
            string json = @"[""1970-01-01T00:00:00Z"",""\/Date(0)\/""]";

            JsonTextReader reader = new JsonTextReader(new StringReader(json));

            reader.DateParseHandling = DateParseHandling.DateTime;

            Assert.IsTrue(await reader.ReadAsync());
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);
            Assert.IsTrue(await reader.ReadAsync());

            reader = new JsonTextReader(new StringReader(json));
            reader.DateParseHandling = DateParseHandling.DateTimeOffset;

            Assert.IsTrue(await reader.ReadAsync());
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero), reader.Value);
            Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType);
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero), reader.Value);
            Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType);
            Assert.IsTrue(await reader.ReadAsync());

            reader = new JsonTextReader(new StringReader(json));
            reader.DateParseHandling = DateParseHandling.None;

            Assert.IsTrue(await reader.ReadAsync());
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(@"1970-01-01T00:00:00Z", reader.Value);
            Assert.AreEqual(typeof(string), reader.ValueType);
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(@"/Date(0)/", reader.Value);
            Assert.AreEqual(typeof(string), reader.ValueType);
            Assert.IsTrue(await reader.ReadAsync());

            reader = new JsonTextReader(new StringReader(json));
            reader.DateParseHandling = DateParseHandling.DateTime;

            Assert.IsTrue(await reader.ReadAsync());
            await reader.ReadAsDateTimeOffsetAsync();

            Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero), reader.Value);
            Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType);
            await reader.ReadAsDateTimeOffsetAsync();

            Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero), reader.Value);
            Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType);
            Assert.IsTrue(await reader.ReadAsync());

            reader = new JsonTextReader(new StringReader(json));
            reader.DateParseHandling = DateParseHandling.DateTimeOffset;

            Assert.IsTrue(await reader.ReadAsync());
            await reader.ReadAsDateTimeAsync();

            Assert.AreEqual(new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);
            await reader.ReadAsDateTimeAsync();

            Assert.AreEqual(new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);
            Assert.IsTrue(await reader.ReadAsync());
        }
        public void Example()
        {
            #region Usage
            string xml = @"<Root type=""Object"">
              <Null type=""Null"" />
              <String type=""String"">This is a string!</String>
              <Char type=""String"">!</Char>
              <Integer type=""Integer"">123</Integer>
              <DateTime type=""Date"">2001-02-22T20:59:59Z</DateTime>
              <DateTimeOffset type=""Date"">2001-02-22T20:59:59+12:00</DateTimeOffset>
              <Float type=""Float"">1.1</Float>
              <Double type=""Float"">3.14</Double>
              <Decimal type=""Float"">19.95</Decimal>
              <Guid type=""Guid"">d66eab59-3715-4b35-9e06-fa61c1216eaa</Guid>
              <Uri type=""Uri"">http://james.newtonking.com</Uri>
              <Array type=""Array"">
                <Item type=""Integer"">1</Item>
                <Item type=""Bytes"">SGVsbG8gd29ybGQh</Item>
                <Item type=""Boolean"">True</Item>
              </Array>
              <Object type=""Object"">
                <String type=""String"">This is a string!</String>
                <Null type=""Null"" />
              </Object>
              <Constructor type=""Constructor"" name=""Date"">
                <Item type=""Integer"">2000</Item>
                <Item type=""Integer"">12</Item>
                <Item type=""Integer"">30</Item>
              </Constructor>
            </Root>";

            StringReader sr = new StringReader(xml);

            using (XmlReader xmlReader = XmlReader.Create(sr, new XmlReaderSettings {
                IgnoreWhitespace = true
            }))
                using (XmlJsonReader reader = new XmlJsonReader(xmlReader))
                {
                    JObject o = JObject.Load(reader);
                    //{
                    //  "Null": null,
                    //  "String": "This is a string!",
                    //  "Char": "!",
                    //  "Integer": 123,
                    //  "DateTime": "2001-02-23T09:59:59+13:00",
                    //  "DateTimeOffset": "2001-02-22T21:59:59+13:00",
                    //  "Float": 1.1,
                    //  "Double": 3.14,
                    //  "Decimal": 19.95,
                    //  "Guid": "d66eab59-3715-4b35-9e06-fa61c1216eaa",
                    //  "Uri": "http://james.newtonking.com",
                    //  "Array": [
                    //    1,
                    //    "SGVsbG8gd29ybGQh",
                    //    true
                    //  ],
                    //  "Object": {
                    //    "String": "This is a string!",
                    //    "Null": null
                    //  },
                    //  "Constructor": new Date(2000, 12, 30)
                    //}
                }
            #endregion

            using (XmlReader xmlReader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings {
                IgnoreWhitespace = true
            }))
                using (XmlJsonReader reader = new XmlJsonReader(xmlReader))
                {
                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.StartObject, reader.TokenType);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Null", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Null, reader.TokenType);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("String", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.String, reader.TokenType);
                    Assert.AreEqual("This is a string!", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Char", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.String, reader.TokenType);
                    Assert.AreEqual("!", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Integer", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Integer, reader.TokenType);
                    Assert.AreEqual(123L, reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("DateTime", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Date, reader.TokenType);
                    Assert.AreEqual(DateTime.Parse("2001-02-22T20:59:59Z"), reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("DateTimeOffset", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Date, reader.TokenType);
                    Assert.AreEqual(DateTime.Parse("2001-02-22T20:59:59+12:00"), reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Float", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Float, reader.TokenType);
                    Assert.AreEqual(1.1d, reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Double", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Float, reader.TokenType);
                    Assert.AreEqual(3.14d, reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Decimal", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Float, reader.TokenType);
                    Assert.AreEqual(19.95d, reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Guid", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.String, reader.TokenType);
                    Assert.AreEqual("d66eab59-3715-4b35-9e06-fa61c1216eaa", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Uri", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.String, reader.TokenType);
                    Assert.AreEqual("http://james.newtonking.com", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Array", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.StartArray, reader.TokenType);

                    Assert.AreEqual(1, reader.ReadAsInt32());
                    Assert.AreEqual(JsonToken.Integer, reader.TokenType);
                    Assert.AreEqual(1L, reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
                    Assert.AreEqual(Encoding.UTF8.GetBytes("Hello world!"), reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Boolean, reader.TokenType);
                    Assert.AreEqual(true, reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.EndArray, reader.TokenType);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Object", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.StartObject, reader.TokenType);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("String", reader.Value);

                    Assert.AreEqual("This is a string!", reader.ReadAsString());
                    Assert.AreEqual(JsonToken.String, reader.TokenType);
                    Assert.AreEqual("This is a string!", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Null", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Null, reader.TokenType);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.EndObject, reader.TokenType);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
                    Assert.AreEqual("Constructor", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.StartConstructor, reader.TokenType);
                    Assert.AreEqual("Date", reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Integer, reader.TokenType);
                    Assert.AreEqual(2000L, reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Integer, reader.TokenType);
                    Assert.AreEqual(12L, reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.Integer, reader.TokenType);
                    Assert.AreEqual(30L, reader.Value);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.EndConstructor, reader.TokenType);

                    Assert.IsTrue(reader.Read());
                    Assert.AreEqual(JsonToken.EndObject, reader.TokenType);

                    Assert.IsFalse(reader.Read());
                }
        }
        public async Task WriteBigIntegerAsync()
        {
            BigInteger i = BigInteger.Parse(
                "1999999999999999999999999999999999999999999999999999999999990"
                );

            MemoryStream ms     = new MemoryStream();
            BsonWriter   writer = new BsonWriter(ms);

            await writer.WriteStartObjectAsync();

            await writer.WritePropertyNameAsync("Blah");

            await writer.WriteValueAsync(i);

            await writer.WriteEndObjectAsync();

            string bson = BytesToHex(ms.ToArray());

            Assert.AreEqual(
                "2A-00-00-00-05-42-6C-61-68-00-1A-00-00-00-00-F6-FF-FF-FF-FF-FF-FF-1F-B2-21-CB-28-59-84-C4-AE-03-8A-44-34-2F-4C-4E-9E-3E-01-00",
                bson
                );

            ms.Seek(0, SeekOrigin.Begin);
            BsonReader reader = new BsonReader(ms);

            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);

            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
            CollectionAssert.AreEqual(
                new byte[]
            {
                246,
                255,
                255,
                255,
                255,
                255,
                255,
                31,
                178,
                33,
                203,
                40,
                89,
                132,
                196,
                174,
                3,
                138,
                68,
                52,
                47,
                76,
                78,
                158,
                62,
                1
            },
                (byte[])reader.Value
                );
            Assert.AreEqual(i, new BigInteger((byte[])reader.Value));

            Assert.IsTrue(await reader.ReadAsync());
            Assert.AreEqual(JsonToken.EndObject, reader.TokenType);

            Assert.IsFalse(await reader.ReadAsync());
        }
Esempio n. 21
0
        public void SupportMultipleContent()
        {
            JsonTextReader reader = new JsonTextReader(new StringReader(@"{'prop1':[1]} 1 2 ""name"" [][]null {}{} 1.1"));

            reader.SupportMultipleContent = true;

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartObject, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartArray, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndArray, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndObject, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.String, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartArray, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndArray, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartArray, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndArray, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Null, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartObject, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndObject, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartObject, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndObject, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Float, reader.TokenType);

            Assert.IsFalse(reader.Read());
        }
        public void ParseDoubles()
        {
            JsonTextReader reader = null;

            reader = new JsonTextReader(new StringReader("1.1"));
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(1.1d, reader.Value);

            reader = new JsonTextReader(new StringReader("-1.1"));
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(-1.1d, reader.Value);

            reader = new JsonTextReader(new StringReader("0.0"));
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(0.0d, reader.Value);

            reader = new JsonTextReader(new StringReader("-0.0"));
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(-0.0d, reader.Value);

            reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd"));
            ExceptionAssert.Throws <JsonReaderException>(() => reader.Read(), "Unexpected character encountered while parsing number: s. Path '', line 1, position 77.");

            reader = new JsonTextReader(new StringReader("1E-06"));
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(0.000001d, reader.Value);

            reader = new JsonTextReader(new StringReader(""));
            Assert.IsFalse(reader.Read());

            reader = new JsonTextReader(new StringReader("-"));
            ExceptionAssert.Throws <JsonReaderException>(() => reader.Read(), "Input string '-' is not a valid number. Path '', line 1, position 1.");

            reader = new JsonTextReader(new StringReader("1.7976931348623157E+308"));
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(Double.MaxValue, reader.Value);

            reader = new JsonTextReader(new StringReader("-1.7976931348623157E+308"));
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(Double.MinValue, reader.Value);

            reader = new JsonTextReader(new StringReader("1E+309"));
            ExceptionAssert.Throws <JsonReaderException>(() => reader.Read(), "Input string '1E+309' is not a valid number. Path '', line 1, position 6.");

            reader = new JsonTextReader(new StringReader("-1E+5000"));
            ExceptionAssert.Throws <JsonReaderException>(() => reader.Read(), "Input string '-1E+5000' is not a valid number. Path '', line 1, position 8.");

            reader = new JsonTextReader(new StringReader("5.1231231E"));
            ExceptionAssert.Throws <JsonReaderException>(() => reader.Read(), "Input string '5.1231231E' is not a valid number. Path '', line 1, position 10.");

            reader = new JsonTextReader(new StringReader("1E-23"));
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(typeof(double), reader.ValueType);
            Assert.AreEqual(1e-23, reader.Value);
        }
Esempio n. 23
0
        public void JValueEquals()
        {
            JObject o = new JObject(
                new JProperty("Null", JValue.CreateNull()),
                new JProperty("Integer", new JValue(1)),
                new JProperty("Float", new JValue(1.1d)),
                new JProperty("Decimal", new JValue(1.1m)),
                new JProperty("DateTime", new JValue(new DateTime(2000, 12, 29, 23, 51, 10, DateTimeKind.Utc))),
                new JProperty("Boolean", new JValue(true)),
                new JProperty("String", new JValue("A string lol!")),
                new JProperty("Bytes", new JValue(Encoding.UTF8.GetBytes("A string lol!"))),
                new JProperty("Uri", new Uri("http://json.codeplex.com/")),
                new JProperty("Guid", new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF")),
                new JProperty("TimeSpan", TimeSpan.FromDays(1))
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3
                , new JProperty("BigInteger", BigInteger.Parse("1"))
#endif
                );

            dynamic d = o;

            Assert.IsTrue(d.Null == d.Null);
            Assert.IsTrue(d.Null == null);
            Assert.IsTrue(d.Null == JValue.CreateNull());
            Assert.IsFalse(d.Null == 1);

            Assert.IsTrue(d.Integer == d.Integer);
            Assert.IsTrue(d.Integer > 0);
            Assert.IsTrue(d.Integer > 0.0m);
            Assert.IsTrue(d.Integer > 0.0f);
            Assert.IsTrue(d.Integer > null);
            Assert.IsTrue(d.Integer >= null);
            Assert.IsTrue(d.Integer == 1);
            Assert.IsTrue(d.Integer == 1m);
            Assert.IsTrue(d.Integer != 1.1f);
            Assert.IsTrue(d.Integer != 1.1d);

            Assert.IsTrue(d.Decimal == d.Decimal);
            Assert.IsTrue(d.Decimal > 0);
            Assert.IsTrue(d.Decimal > 0.0m);
            Assert.IsTrue(d.Decimal > 0.0f);
            Assert.IsTrue(d.Decimal > null);
            Assert.IsTrue(d.Decimal >= null);
            Assert.IsTrue(d.Decimal == 1.1);
            Assert.IsTrue(d.Decimal == 1.1m);
            Assert.IsTrue(d.Decimal != 1.0f);
            Assert.IsTrue(d.Decimal != 1.0d);
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3
            Assert.IsTrue(d.Decimal > new BigInteger(0));
#endif

            Assert.IsTrue(d.Float == d.Float);
            Assert.IsTrue(d.Float > 0);
            Assert.IsTrue(d.Float > 0.0m);
            Assert.IsTrue(d.Float > 0.0f);
            Assert.IsTrue(d.Float > null);
            Assert.IsTrue(d.Float >= null);
            Assert.IsTrue(d.Float < 2);
            Assert.IsTrue(d.Float <= 1.1);
            Assert.IsTrue(d.Float == 1.1);
            Assert.IsTrue(d.Float == 1.1m);
            Assert.IsTrue(d.Float != 1.0f);
            Assert.IsTrue(d.Float != 1.0d);
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3
            Assert.IsTrue(d.Float > new BigInteger(0));
#endif

#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3
            Assert.IsTrue(d.BigInteger == d.BigInteger);
            Assert.IsTrue(d.BigInteger > 0);
            Assert.IsTrue(d.BigInteger > 0.0m);
            Assert.IsTrue(d.BigInteger > 0.0f);
            Assert.IsTrue(d.BigInteger > null);
            Assert.IsTrue(d.BigInteger >= null);
            Assert.IsTrue(d.BigInteger < 2);
            Assert.IsTrue(d.BigInteger <= 1.1);
            Assert.IsTrue(d.BigInteger == 1);
            Assert.IsTrue(d.BigInteger == 1m);
            Assert.IsTrue(d.BigInteger != 1.1f);
            Assert.IsTrue(d.BigInteger != 1.1d);
#endif

            Assert.IsTrue(d.Bytes == d.Bytes);
            Assert.IsTrue(d.Bytes == Encoding.UTF8.GetBytes("A string lol!"));
            Assert.IsTrue(d.Bytes == new JValue(Encoding.UTF8.GetBytes("A string lol!")));

            Assert.IsTrue(d.Uri == d.Uri);
            Assert.IsTrue(d.Uri == new Uri("http://json.codeplex.com/"));
            Assert.IsTrue(d.Uri > new Uri("http://abc.org/"));
            Assert.IsTrue(d.Uri >= new Uri("http://abc.com/"));
            Assert.IsTrue(d.Uri > null);
            Assert.IsTrue(d.Uri >= null);

            Assert.IsTrue(d.Guid == d.Guid);
            Assert.IsTrue(d.Guid == new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF"));
            Assert.IsTrue(d.Guid > new Guid("AAAAAAAA-0D80-44F2-BF34-4654156FA7AF"));
            Assert.IsTrue(d.Guid >= new Guid("AAAAAAAA-0D80-44F2-BF34-4654156FA7AF"));
            Assert.IsTrue(d.Guid > null);
            Assert.IsTrue(d.Guid >= null);

            Assert.IsTrue(d.TimeSpan == d.TimeSpan);
            Assert.IsTrue(d.TimeSpan == TimeSpan.FromDays(1));
            Assert.IsTrue(d.TimeSpan > TimeSpan.FromHours(1));
            Assert.IsTrue(d.TimeSpan >= TimeSpan.FromHours(1));
            Assert.IsTrue(d.TimeSpan > null);
            Assert.IsTrue(d.TimeSpan >= null);
        }
        public void DateParseHandling()
        {
            string json = @"[""1970-01-01T00:00:00Z"",""\/Date(0)\/""]";

            JsonTextReader reader = new JsonTextReader(new StringReader(json));

            reader.DateParseHandling = Json.DateParseHandling.DateTime;

            Assert.IsTrue(reader.Read());
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);
            Assert.IsTrue(reader.Read());

#if !NET20
            reader = new JsonTextReader(new StringReader(json));
            reader.DateParseHandling = Json.DateParseHandling.DateTimeOffset;

            Assert.IsTrue(reader.Read());
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero), reader.Value);
            Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType);
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero), reader.Value);
            Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType);
            Assert.IsTrue(reader.Read());
#endif

            reader = new JsonTextReader(new StringReader(json));
            reader.DateParseHandling = Json.DateParseHandling.None;

            Assert.IsTrue(reader.Read());
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(@"1970-01-01T00:00:00Z", reader.Value);
            Assert.AreEqual(typeof(string), reader.ValueType);
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(@"/Date(0)/", reader.Value);
            Assert.AreEqual(typeof(string), reader.ValueType);
            Assert.IsTrue(reader.Read());

#if !NET20
            reader = new JsonTextReader(new StringReader(json));
            reader.DateParseHandling = Json.DateParseHandling.DateTime;

            Assert.IsTrue(reader.Read());
            reader.ReadAsDateTimeOffset();
            Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero), reader.Value);
            Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType);
            reader.ReadAsDateTimeOffset();
            Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero), reader.Value);
            Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType);
            Assert.IsTrue(reader.Read());

            reader = new JsonTextReader(new StringReader(json));
            reader.DateParseHandling = Json.DateParseHandling.DateTimeOffset;

            Assert.IsTrue(reader.Read());
            reader.ReadAsDateTime();
            Assert.AreEqual(new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);
            reader.ReadAsDateTime();
            Assert.AreEqual(new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);
            Assert.IsTrue(reader.Read());
#endif
        }