public void CreateFromDynamicWithJsonValueChildrenTest()
        {
            JsonValue target;
            string    level3   = "{\"Name\":\"Level3\",\"Null\":null}";
            string    level2   = "{\"Name\":\"Level2\",\"JsonObject\":" + AnyInstance.AnyJsonObject.ToString() + ",\"JsonArray\":" + AnyInstance.AnyJsonArray.ToString() + ",\"Level3\":" + level3 + "}";
            string    level1   = "{\"Name\":\"Level1\",\"JsonPrimitive\":" + AnyInstance.AnyJsonPrimitive.ToString() + ",\"Level2\":" + level2 + "}";
            string    expected = "{\"Name\":\"Root\",\"Level1\":" + level1 + "}";

            dynamic dyn = new TestDynamicObject();

            dyn.Name                      = "Root";
            dyn.Level1                    = new TestDynamicObject();
            dyn.Level1.Name               = "Level1";
            dyn.Level1.JsonPrimitive      = AnyInstance.AnyJsonPrimitive;
            dyn.Level1.Level2             = new TestDynamicObject();
            dyn.Level1.Level2.Name        = "Level2";
            dyn.Level1.Level2.JsonObject  = AnyInstance.AnyJsonObject;
            dyn.Level1.Level2.JsonArray   = AnyInstance.AnyJsonArray;
            dyn.Level1.Level2.Level3      = new TestDynamicObject();
            dyn.Level1.Level2.Level3.Name = "Level3";
            dyn.Level1.Level2.Level3.Null = null;

            target = JsonValueExtensions.CreateFrom(dyn);
            Assert.Equal <string>(expected, target.ToString());
        }
Esempio n. 2
0
        public void PropertyAccessTest()
        {
            Person        p  = AnyInstance.AnyPerson;
            JsonObject    jo = JsonValueExtensions.CreateFrom(p) as JsonObject;
            JsonArray     ja = JsonValueExtensions.CreateFrom(p.Friends) as JsonArray;
            JsonPrimitive jp = AnyInstance.AnyJsonPrimitive;
            JsonValue     jv = AnyInstance.DefaultJsonValue;

            dynamic jod = jo;
            dynamic jad = ja;
            dynamic jpd = jp;
            dynamic jvd = jv;

            Assert.Equal(jo.Count, jod.Count);
            Assert.Equal(jo.JsonType, jod.JsonType);
            Assert.Equal(jo.Keys.Count, jod.Keys.Count);
            Assert.Equal(jo.Values.Count, jod.Values.Count);
            Assert.Equal(p.Age, (int)jod.Age);
            Assert.Equal(p.Age, (int)jod["Age"]);
            Assert.Equal(p.Age, (int)jo["Age"]);
            Assert.Equal(p.Address.City, (string)jo["Address"]["City"]);
            Assert.Equal(p.Address.City, (string)jod["Address"]["City"]);
            Assert.Equal(p.Address.City, (string)jod.Address.City);

            Assert.Equal(p.Friends.Count, ja.Count);
            Assert.Equal(ja.Count, jad.Count);
            Assert.Equal(ja.IsReadOnly, jad.IsReadOnly);
            Assert.Equal(ja.JsonType, jad.JsonType);
            Assert.Equal(p.Friends[0].Age, (int)ja[0]["Age"]);
            Assert.Equal(p.Friends[0].Age, (int)jad[0].Age);

            Assert.Equal(jp.JsonType, jpd.JsonType);
        }
Esempio n. 3
0
        public void CreateFromDateTimeTest()
        {
            DateTime       dt  = DateTime.Now;
            DateTimeOffset dto = DateTimeOffset.Now;

            JsonValue jvDt1 = (JsonValue)dt;
            JsonValue jvDt2 = JsonValueExtensions.CreateFrom(dt);

            JsonValue jvDto1 = (JsonValue)dto;
            JsonValue jvDto2 = JsonValueExtensions.CreateFrom(dto);

            Assert.Equal(dt, (DateTime)jvDt1);
            Assert.Equal(dt, (DateTime)jvDt2);

            Assert.Equal(dto, (DateTimeOffset)jvDto1);
            Assert.Equal(dto, (DateTimeOffset)jvDto2);

            Assert.Equal(dt, jvDt1.ReadAs <DateTime>());
            Assert.Equal(dt, jvDt2.ReadAs <DateTime>());

            Assert.Equal(dto, jvDto1.ReadAs <DateTimeOffset>());
            Assert.Equal(dto, jvDto2.ReadAs <DateTimeOffset>());

            Assert.Equal(jvDt1.ToString(), jvDt2.ToString());
            Assert.Equal(jvDto1.ToString(), jvDto2.ToString());
        }
        public void CreateFromComplexTypeTest()
        {
            Assert.Null(JsonValueExtensions.CreateFrom(null));

            Person anyObject = AnyInstance.AnyPerson;

            JsonObject jv = JsonValueExtensions.CreateFrom(anyObject) as JsonObject;

            Assert.NotNull(jv);
            Assert.Equal(4, jv.Count);
            foreach (string key in "Name Age Address".Split())
            {
                Assert.True(jv.ContainsKey(key));
            }

            Assert.Equal(AnyInstance.AnyString, (string)jv["Name"]);
            Assert.Equal(AnyInstance.AnyInt, (int)jv["Age"]);

            JsonObject nestedObject = jv["Address"] as JsonObject;

            Assert.NotNull(nestedObject);
            Assert.Equal(3, nestedObject.Count);
            foreach (string key in "Street City State".Split())
            {
                Assert.True(nestedObject.ContainsKey(key));
            }

            Assert.Equal(Address.AnyStreet, (string)nestedObject["Street"]);
            Assert.Equal(Address.AnyCity, (string)nestedObject["City"]);
            Assert.Equal(Address.AnyState, (string)nestedObject["State"]);
        }
        public void GetValueOrDefaultTest()
        {
            bool      boolValue;
            JsonValue target;
            JsonValue jsonValue;

            Person     person = AnyInstance.AnyPerson;
            JsonObject jo     = JsonValueExtensions.CreateFrom(person) as JsonObject;

            Assert.Equal <int>(person.Age, jo.ValueOrDefault("Age").ReadAs <int>());                                          // JsonPrimitive

            Assert.Equal <string>(person.Address.ToString(), jo.ValueOrDefault("Address").ReadAsType <Address>().ToString()); // JsonObject
            Assert.Equal <int>(person.Friends.Count, jo.ValueOrDefault("Friends").Count);                                     // JsonArray

            target = jo.ValueOrDefault("Address").ValueOrDefault("City");                                                     // JsonPrimitive
            Assert.NotNull(target);
            Assert.Equal <string>(person.Address.City, target.ReadAs <string>());

            target = jo.ValueOrDefault("Address", "City"); // JsonPrimitive
            Assert.NotNull(target);
            Assert.Equal <string>(person.Address.City, target.ReadAs <string>());

            target = jo.ValueOrDefault("Address").ValueOrDefault("NonExistentProp").ValueOrDefault("NonExistentProp2"); // JsonObject
            Assert.Equal(JsonType.Default, target.JsonType);
            Assert.NotNull(target);
            Assert.False(target.TryReadAs <bool>(out boolValue));
            Assert.True(target.TryReadAs <JsonValue>(out jsonValue));

            target = jo.ValueOrDefault("Address", "NonExistentProp", "NonExistentProp2"); // JsonObject
            Assert.Equal(JsonType.Default, target.JsonType);
            Assert.NotNull(target);
            Assert.False(target.TryReadAs <bool>(out boolValue));
            Assert.True(target.TryReadAs <JsonValue>(out jsonValue));
            Assert.Same(target, jsonValue);
        }
        public void CreateFromDynamicComplextTest()
        {
            JsonValue target;
            Person    person = AnyInstance.AnyPerson;
            dynamic   dyn    = TestDynamicObject.CreatePersonAsDynamic(person);

            dyn.TestProperty = AnyInstance.AnyString;

            target = JsonValueExtensions.CreateFrom(dyn);
            Assert.NotNull(target);
            Assert.Equal <string>(AnyInstance.AnyString, dyn.TestProperty);
            Person jvPerson = target.ReadAsType <Person>();

            Assert.Equal(person.ToString(), jvPerson.ToString());

            Person p1 = Person.CreateSample();
            Person p2 = Person.CreateSample();

            p2.Name         += "__2";
            p2.Age          += 10;
            p2.Address.City += "__2";

            Person[] friends = new Person[] { p1, p2 };
            target = JsonValueExtensions.CreateFrom(friends);
            Person[] personArr = target.ReadAsType <Person[]>();
            Assert.Equal <int>(friends.Length, personArr.Length);
            Assert.Equal <string>(friends[0].ToString(), personArr[0].ToString());
            Assert.Equal <string>(friends[1].ToString(), personArr[1].ToString());
        }
        public void CreateFromDeepNestedDynamic()
        {
            int    count    = 5000;
            string expected = "";

            dynamic dyn = new TestDynamicObject();
            dynamic cur = dyn;

            for (int i = 0; i < count; i++)
            {
                expected         += "{\"" + i + "\":";
                cur[i.ToString()] = new TestDynamicObject();
                cur = cur[i.ToString()];
            }

            expected += "{}";

            for (int i = 0; i < count; i++)
            {
                expected += "}";
            }

            JsonValue jv = JsonValueExtensions.CreateFrom(dyn);

            Assert.Equal(expected, jv.ToString());
        }
        public void CreateFromComplexTest()
        {
            JsonValue target = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);

            Assert.Equal(AnyInstance.AnyPerson.Name, (string)target["Name"]);
            Assert.Equal(AnyInstance.AnyPerson.Age, (int)target["Age"]);
            Assert.Equal(AnyInstance.AnyPerson.Address.City, (string)target.ValueOrDefault("Address", "City"));
        }
Esempio n. 9
0
        public void CastTests()
        {
            dynamic dyn  = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson) as JsonObject;
            string  city = dyn.Address.City;

            Assert.Equal <string>(AnyInstance.AnyPerson.Address.City, dyn.Address.City.ReadAs <string>());
            Assert.Equal <string>(AnyInstance.AnyPerson.Address.City, city);

            JsonValue[] values =
            {
                AnyInstance.AnyInt,
                AnyInstance.AnyString,
                AnyInstance.AnyDateTime,
                AnyInstance.AnyJsonObject,
                AnyInstance.AnyJsonArray,
                AnyInstance.DefaultJsonValue
            };

            int  loopCount    = 2;
            bool explicitCast = true;

            while (loopCount > 0)
            {
                loopCount--;

                foreach (JsonValue jv in values)
                {
                    EvaluateNoExceptions <JsonValue>(null, explicitCast);
                    EvaluateNoExceptions <JsonValue>(jv, explicitCast);
                    EvaluateNoExceptions <object>(jv, explicitCast);
                    EvaluateNoExceptions <IDynamicMetaObjectProvider>(jv, explicitCast);
                    EvaluateNoExceptions <IEnumerable <KeyValuePair <string, JsonValue> > >(jv, explicitCast);
                    EvaluateNoExceptions <string>(null, explicitCast);

                    EvaluateExpectExceptions <int>(null, explicitCast);
                    EvaluateExpectExceptions <Person>(jv, explicitCast);
                    EvaluateExpectExceptions <Exception>(jv, explicitCast);

                    EvaluateIgnoreExceptions <JsonObject>(jv, explicitCast);
                    EvaluateIgnoreExceptions <int>(jv, explicitCast);
                    EvaluateIgnoreExceptions <string>(jv, explicitCast);
                    EvaluateIgnoreExceptions <DateTime>(jv, explicitCast);
                    EvaluateIgnoreExceptions <JsonArray>(jv, explicitCast);
                    EvaluateIgnoreExceptions <JsonPrimitive>(jv, explicitCast);
                }

                explicitCast = false;
            }

            EvaluateNoExceptions <IDictionary <string, JsonValue> >(AnyInstance.AnyJsonObject, false);
            EvaluateNoExceptions <IList <JsonValue> >(AnyInstance.AnyJsonArray, false);
        }
Esempio n. 10
0
        public void CreateFromTests()
        {
            InstanceCreatorSurrogate oldSurrogate = CreatorSettings.CreatorSurrogate;

            try
            {
                CreatorSettings.CreatorSurrogate = new NoInfinityFloatSurrogate();
                DateTime now  = DateTime.Now;
                int      seed = (10000 * now.Year) + (100 * now.Month) + now.Day;
                Log.Info("Seed: {0}", seed);
                Random rndGen = new Random(seed);
                foreach (Type testType in testTypes)
                {
                    object    instance = InstanceCreator.CreateInstanceOf(testType, rndGen);
                    JsonValue jv       = JsonValueExtensions.CreateFrom(instance);

                    if (instance == null)
                    {
                        Assert.Null(jv);
                    }
                    else
                    {
                        DataContractJsonSerializer dcjs = new DataContractJsonSerializer(instance == null ? testType : instance.GetType());
                        string fromDCJS;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            dcjs.WriteObject(ms, instance);
                            fromDCJS = Encoding.UTF8.GetString(ms.ToArray());
                        }

                        Log.Info("{0}: {1}", testType.Name, fromDCJS);

                        if (instance == null)
                        {
                            Assert.Null(jv);
                        }
                        else
                        {
                            string fromJsonValue = jv.ToString();
                            Assert.Equal(fromDCJS, fromJsonValue);
                        }
                    }
                }
            }
            finally
            {
                CreatorSettings.CreatorSurrogate = oldSurrogate;
            }
        }
        public void CreateFromTypeTest()
        {
            JsonValue[] values =
            {
                AnyInstance.AnyJsonObject,
                AnyInstance.AnyJsonArray,
                AnyInstance.AnyJsonPrimitive,
                AnyInstance.DefaultJsonValue
            };

            foreach (JsonValue value in values)
            {
                Assert.Same(value, JsonValueExtensions.CreateFrom(value));
            }
        }
        public void ReadAsExtensionsOnDynamicTest()
        {
            dynamic jv = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            bool    success;
            object  obj;

            success = jv.TryReadAsType(typeof(Person), out obj);
            Assert.True(success);
            Assert.NotNull(obj);
            Assert.Equal <string>(AnyInstance.AnyPerson.ToString(), obj.ToString());

            obj = jv.ReadAsType(typeof(Person));
            Assert.NotNull(obj);
            Assert.Equal <string>(AnyInstance.AnyPerson.ToString(), obj.ToString());
        }
        // 195843 JsonValue to support generic extension methods defined in JsonValueExtensions.
        // 195867 Consider creating extension point for allowing new extension methods to be callable via dynamic interface
        //[Fact] This requires knowledge of the C# binder to be able to get the generic call parameters.
        public void ReadAsGenericExtensionsOnDynamicTest()
        {
            dynamic jv = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            Person  person;
            bool    success;

            person = jv.ReadAsType <Person>();
            Assert.NotNull(person);
            Assert.Equal <string>(AnyInstance.AnyPerson.ToString(), person.ToString());

            success = jv.TryReadAsType <Person>(out person);
            Assert.True(success);
            Assert.NotNull(person);
            Assert.Equal <string>(AnyInstance.AnyPerson.ToString(), person.ToString());
        }
        public void CreateFromNestedDynamicTest()
        {
            JsonValue target;
            string    expected = "{\"Name\":\"Root\",\"Level1\":{\"Name\":\"Level1\",\"Level2\":{\"Name\":\"Level2\"}}}";
            dynamic   dyn      = new TestDynamicObject();

            dyn.Name               = "Root";
            dyn.Level1             = new TestDynamicObject();
            dyn.Level1.Name        = "Level1";
            dyn.Level1.Level2      = new TestDynamicObject();
            dyn.Level1.Level2.Name = "Level2";

            target = JsonValueExtensions.CreateFrom(dyn);
            Assert.NotNull(target);
            Assert.Equal <string>(expected, target.ToString());
        }
        public void CreateFromDynamicBinderFallbackTest()
        {
            JsonValue target;
            Person    person = AnyInstance.AnyPerson;
            dynamic   dyn    = new TestDynamicObject();

            dyn.Name = AnyInstance.AnyString;

            dyn.UseFallbackMethod = true;
            string expectedMessage = String.Format(DynamicPropertyNotDefined, dyn.GetType().FullName, "Name");

            ExceptionHelper.Throws <InvalidOperationException>(() => target = JsonValueExtensions.CreateFrom(dyn), expectedMessage);

            dyn.UseErrorSuggestion = true;
            ExceptionHelper.Throws <TestDynamicObject.TestDynamicObjectException>(() => target = JsonValueExtensions.CreateFrom(dyn));
        }
        public void DefaultConcatTest()
        {
            JsonValue jv     = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            dynamic   target = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            Person    person = AnyInstance.AnyPerson;

            Assert.Equal(person.Address.City, target.Address.City.ReadAs <string>());
            Assert.Equal(person.Friends[0].Age, target.Friends[0].Age.ReadAs <int>());

            Assert.Equal(target.ValueOrDefault("Address").ValueOrDefault("City"), target.Address.City);
            Assert.Equal(target.ValueOrDefault("Address", "City"), target.Address.City);

            Assert.Equal(target.ValueOrDefault("Friends").ValueOrDefault(0).ValueOrDefault("Age"), target.Friends[0].Age);
            Assert.Equal(target.ValueOrDefault("Friends", 0, "Age"), target.Friends[0].Age);

            Assert.Equal(JsonType.Default, AnyInstance.AnyJsonValue1.ValueOrDefault((object[])null).JsonType);
            Assert.Equal(JsonType.Default, jv.ValueOrDefault("Friends", null).JsonType);
            Assert.Equal(JsonType.Default, AnyInstance.AnyJsonValue1.ValueOrDefault((string)null).JsonType);
            Assert.Equal(JsonType.Default, AnyInstance.AnyJsonPrimitive.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyShort).JsonType);
            Assert.Equal(JsonType.Default, AnyInstance.AnyJsonArray.ValueOrDefault((string)null).JsonType);
            Assert.Equal(JsonType.Default, AnyInstance.AnyJsonObject.ValueOrDefault(AnyInstance.AnyString, null).JsonType);
            Assert.Equal(JsonType.Default, AnyInstance.AnyJsonArray.ValueOrDefault(-1).JsonType);

            Assert.Same(AnyInstance.AnyJsonValue1, AnyInstance.AnyJsonValue1.ValueOrDefault());

            Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((short)0));
            Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((ushort)0));
            Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((byte)0));
            Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((sbyte)0));
            Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((char)0));

            jv = new JsonObject();
            jv[AnyInstance.AnyString] = AnyInstance.AnyJsonArray;

            Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (short)0));
            Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (ushort)0));
            Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (byte)0));
            Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (sbyte)0));
            Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (char)0));

            jv = AnyInstance.AnyJsonObject;

            ExceptionHelper.Throws <ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyLong); }, String.Format(InvalidIndexType, typeof(long)));
            ExceptionHelper.Throws <ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyUInt); }, String.Format(InvalidIndexType, typeof(uint)));
            ExceptionHelper.Throws <ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyBool); }, String.Format(InvalidIndexType, typeof(bool)));
        }
        public void CreateFromDynamicJVTest()
        {
            JsonValue target;

            dynamic[] values = new dynamic[]
            {
                AnyInstance.AnyJsonArray,
                AnyInstance.AnyJsonObject,
                AnyInstance.AnyJsonPrimitive,
                AnyInstance.DefaultJsonValue
            };

            foreach (dynamic dyn in values)
            {
                target = JsonValueExtensions.CreateFrom(dyn);
                Assert.Same(dyn, target);
            }
        }
        public void TestDataContractJsonSerializerSettings()
        {
            TestTypeForSerializerSettings instance = new TestTypeForSerializerSettings
            {
                BaseRef = new DerivedType(),
                Date    = AnyInstance.AnyDateTime,
                Dict    = new Dictionary <string, object>
                {
                    { "one", 1 },
                    { "two", 2 },
                    { "two point five", 2.5 },
                }
            };

            JsonObject dict = new JsonObject
            {
                { "one", 1 },
                { "two", 2 },
                { "two point five", 2.5 },
            };

            JsonObject equivalentJsonObject = new JsonObject
            {
                { "BaseRef", new JsonObject {
                      { "__type", "DerivedType:NS" }
                  } },
                { "Date", AnyInstance.AnyDateTime },
                { "Dict", dict },
            };

            JsonObject createdFromType = JsonValueExtensions.CreateFrom(instance) as JsonObject;

            Assert.Equal(equivalentJsonObject.ToString(), createdFromType.ToString());

            TestTypeForSerializerSettings newInstance = equivalentJsonObject.ReadAsType <TestTypeForSerializerSettings>();

            // DISABLED, 198487 - Assert.Equal(instance.Date, newInstance.Date);
            Assert.Equal(instance.BaseRef.GetType().FullName, newInstance.BaseRef.GetType().FullName);
            Assert.Equal(3, newInstance.Dict.Count);
            Assert.Equal(1, newInstance.Dict["one"]);
            Assert.Equal(2, newInstance.Dict["two"]);
            Assert.Equal(2.5, Convert.ToDouble(newInstance.Dict["two point five"], CultureInfo.InvariantCulture));
        }
Esempio n. 19
0
        public void DefaultConcatTest()
        {
            JsonValue jv     = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            dynamic   target = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            Person    person = AnyInstance.AnyPerson;

            Assert.Equal(JsonType.Default, target.Friends[100000].Name.JsonType);
            Assert.Equal(JsonType.Default, target.Friends[0].Age.Minutes.JsonType);

            JsonValue jv1 = target.MissingProperty as JsonValue;

            Assert.NotNull(jv1);

            JsonValue jv2 = target.MissingProperty1.MissingProperty2 as JsonValue;

            Assert.NotNull(jv2);

            Assert.Same(jv1, jv2);
            Assert.Same(target.Person.Name.MissingProperty, AnyInstance.DefaultJsonValue);
        }
        public void CreateFromDynamicSimpleTest()
        {
            JsonValue target;

            target = JsonValueExtensions.CreateFrom(AnyInstance.AnyDynamic);
            Assert.NotNull(target);

            string  expected = "{\"Name\":\"Bill Gates\",\"Age\":21,\"Grades\":[\"F\",\"B-\",\"C\"]}";
            dynamic obj      = new TestDynamicObject();

            obj.Name   = "Bill Gates";
            obj.Age    = 21;
            obj.Grades = new[] { "F", "B-", "C" };

            target = JsonValueExtensions.CreateFrom(obj);
            Assert.Equal <string>(expected, target.ToString());

            target = JsonValueExtensions.CreateFrom(new TestDynamicObject());
            Assert.Equal <string>("{}", target.ToString());
        }
Esempio n. 21
0
        public void CreateFromDynamic()
        {
            string          expectedJson = "{\"int\":12,\"str\":\"hello\",\"jv\":[1,{\"a\":true}],\"dyn\":{\"char\":\"c\",\"null\":null}}";
            MyDynamicObject obj          = new MyDynamicObject();

            obj.fields.Add("int", 12);
            obj.fields.Add("str", "hello");
            obj.fields.Add("jv", new JsonArray(1, new JsonObject {
                { "a", true }
            }));
            MyDynamicObject dyn = new MyDynamicObject();

            obj.fields.Add("dyn", dyn);
            dyn.fields.Add("char", 'c');
            dyn.fields.Add("null", null);

            JsonValue jv = JsonValueExtensions.CreateFrom(obj);

            Assert.Equal(expectedJson, jv.ToString());
        }
        /// <summary>
        /// Tests for <see cref="JsonValue"/> instances without dynamic references.
        /// </summary>
        public void NonDynamicTest()
        {
            int seed = GetRandomSeed();

            Log.Info("Seed: {0}", seed);
            Random rndGen = new Random(seed);

            AssertIsTrue(Assembly.GetExecutingAssembly().IsFullyTrusted == false, "Executing assembly not expected to be fully trusted!");

            Person person  = new Person(rndGen);
            Person person2 = new Person(rndGen);

            person.AddFriends(3, rndGen);
            person2.AddFriends(3, rndGen);

            JsonValue jo  = JsonValueExtensions.CreateFrom(person);
            JsonValue jo2 = JsonValueExtensions.CreateFrom(person2);

            AssertAreEqual(person.Address.City, jo["Address"]["City"].ReadAs <string>(), "Address.City");
            AssertAreEqual(person.Friends[1].Age, jo["Friends"][1]["Age"].ReadAs <int>(), "Friends[1].Age");

            string newCityName = "Bellevue";

            jo["Address"]["City"] = newCityName;
            AssertAreEqual(newCityName, (string)jo["Address"]["City"], "Address.City2");

            jo["Friends"][1] = jo2;
            AssertAreEqual(person2.Age, (int)jo["Friends"][1]["Age"], "Friends[1].Age2");

            AssertAreEqual(person2.Address.City, jo.ValueOrDefault("Friends").ValueOrDefault(1).ValueOrDefault("Address").ValueOrDefault("City").ReadAs <string>(), "Address.City3");
            AssertAreEqual(person2.Age, (int)jo.ValueOrDefault("Friends").ValueOrDefault(1).ValueOrDefault("Age"), "Friends[1].Age3");

            AssertAreEqual(person2.Address.City, jo.ValueOrDefault("Friends", 1, "Address", "City").ReadAs <string>(), "Address.City3");
            AssertAreEqual(person2.Age, (int)jo.ValueOrDefault("Friends", 1, "Age"), "Friends[1].Age3");

            int       newAge   = 42;
            JsonValue ageValue = jo["Friends"][1]["Age"] = newAge;

            AssertAreEqual(newAge, (int)ageValue, "Friends[1].Age4");
        }
Esempio n. 23
0
        public void DynamicNotationTest()
        {
            bool      boolValue;
            JsonValue jsonValue;

            Person  person = Person.CreateSample();
            dynamic jo     = JsonValueExtensions.CreateFrom(person);

            dynamic target = jo;

            Assert.Equal <int>(person.Age, target.Age.ReadAs <int>());                                                        // JsonPrimitive
            Assert.Equal <string>(person.Address.ToString(), ((JsonObject)target.Address).ReadAsType <Address>().ToString()); // JsonObject

            target = jo.Address.City;                                                                                         // JsonPrimitive
            Assert.NotNull(target);
            Assert.Equal <string>(target.ReadAs <string>(), person.Address.City);

            target = jo.Friends;  // JsonArray
            Assert.NotNull(target);
            jsonValue = target as JsonValue;
            Assert.Equal <int>(person.Friends.Count, jsonValue.ReadAsType <List <Person> >().Count);

            target = jo.Friends[1].Address.City;
            Assert.NotNull(target);
            Assert.Equal <string>(target.ReadAs <string>(), person.Address.City);

            target = jo.Address.NonExistentProp.NonExistentProp2; // JsonObject (default)
            Assert.NotNull(target);
            Assert.True(jo is JsonObject);
            Assert.False(target.TryReadAs <bool>(out boolValue));
            Assert.True(target.TryReadAs <JsonValue>(out jsonValue));
            Assert.Same(target, jsonValue);

            Assert.Same(jo.Address.NonExistent, AnyInstance.DefaultJsonValue);
            Assert.Same(jo.Friends[1000], AnyInstance.DefaultJsonValue);
            Assert.Same(jo.Age.NonExistentProp, AnyInstance.DefaultJsonValue);
            Assert.Same(jo.Friends.NonExistentProp, AnyInstance.DefaultJsonValue);
        }
        /// <summary>
        /// Tests for <see cref="JsonValue"/> instances with dynamic references.
        /// </summary>
        public void DynamicTest()
        {
            int seed = GetRandomSeed();

            Log.Info("Seed: {0}", seed);
            Random rndGen = new Random(seed);

            AssertIsTrue(Assembly.GetExecutingAssembly().IsFullyTrusted == false, "Executing assembly not expected to be fully trusted!");

            Person person = new Person(rndGen);

            person.AddFriends(1, rndGen);

            dynamic jo = JsonValueExtensions.CreateFrom(person);

            AssertAreEqual(person.Friends[0].Name, jo.Friends[0].Name.ReadAs <string>(), "Friends[0].Name");
            AssertAreEqual(person.Address.City, jo.Address.City.ReadAs <string>(), "Address.City");
            AssertAreEqual(person.Friends[0].Age, (int)jo.Friends[0].Age, "Friends[0].Age");

            string newCityName = "Bellevue";

            jo.Address.City = newCityName;
            AssertAreEqual(newCityName, (string)jo.Address.City, "Address.City2");

            AssertAreEqual(person.Friends[0].Address.City, jo.ValueOrDefault("Friends").ValueOrDefault(0).ValueOrDefault("Address").ValueOrDefault("City").ReadAs <string>(), "Friends[0].Address.City");
            AssertAreEqual(person.Friends[0].Age, (int)jo.ValueOrDefault("Friends").ValueOrDefault(0).ValueOrDefault("Age"), "Friends[0].Age2");

            AssertAreEqual(person.Friends[0].Address.City, jo.ValueOrDefault("Friends", 0, "Address", "City").ReadAs <string>(), "Friends[0].Address.City");
            AssertAreEqual(person.Friends[0].Age, (int)jo.ValueOrDefault("Friends", 0, "Age"), "Friends[0].Age2");

            int       newAge   = 42;
            JsonValue ageValue = jo.Friends[0].Age = newAge;

            AssertAreEqual(newAge, (int)ageValue, "Friends[0].Age3");

            AssertIsTrue(jo.NonExistentProperty is JsonValue, "Expected a JsonValue");
            AssertIsTrue(jo.NonExistentProperty.JsonType == JsonType.Default, "Expected default JsonValue");
        }
        public void CreateFromPrimitiveTest(object value)
        {
            Type valueType = value.GetType();

            Assert.Equal(value, JsonValueExtensions.CreateFrom(value).ReadAs(valueType));
        }