Esempio n. 1
0
        public void GetValueTest()
        {
            dynamic dyn = new DynObject();

            dyn.Add("foo", "bar");
            Assert.AreEqual("bar", dyn.GetValue("foo"));
            Assert.AreEqual(null, dyn.GetValue("baz"));
            Assert.AreEqual("notbar", dyn.GetValue("baz", "notbar"));
        } // end AccessorTest
        public static JToken Serialize(this DynObject value)
        {
            JToken result = null;
            object v      = value.GetValue != null?value.GetValue(null) : null;

            if (v != null)
            {
                if (v is string s)
                {
                    if (!string.IsNullOrEmpty(s))
                    {
                        result = new JValue(v);
                    }
                }
                else
                {
                    result = new JValue(v);
                }
            }
            else
            {
                if (value.IsArray)
                {
                    var ar = new JArray();
                    foreach (var item in value.Items)
                    {
                        var r = Serialize(item.Value);
                        if (r != null)
                        {
                            ar.Add(r);
                        }
                    }
                    if (ar.Count > 0)
                    {
                        result = ar;
                    }
                }
                else
                {
                    var oj = new JObject();
                    foreach (var item in value.Items)
                    {
                        var r = Serialize(item.Value);
                        if (r != null)
                        {
                            oj.Add(new JProperty(item.Key, r));
                        }
                    }
                    if (oj.Count > 0)
                    {
                        result = oj;
                    }
                }
            }

            if (result == null)
            {
                result = new JObject();
            }

            return(result);
        }