Quantcast
Channel: 黑暗執行緒
Viewing all articles
Browse latest Browse all 2311

使用dynamic簡化Json.NET JObject操作

$
0
0

不知是RSS ATOM錯亂還是怎麼的,feedly RSS閱讀器冒出一篇Rick Strahl 2012的老文章 Using JSON.NET for dynamic JSON parsing ,讓我大吃一驚,發現自己一直用JProperty的笨拙方法處理動態JSON物件,其實結合dynamic就能大幅簡化。莫名其妙讀到兩年多前的文章,是老天爺的安排吧?擔心不順從天意會遭天譴,特筆記分享之。XD

以下範例示範使用強型別物件、JObject+JProperty、JObject+dymanic三種不同做法,處理JSON反序列化及序列化。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace JsonNetLab
{
class Program
    {
staticvoid Main(string[] args)
        {
            lab1();
            lab2();
            lab3();
            lab4();
            lab5();
            lab6();
            Console.Read();
        }
staticstring jsonSrc = 
@"{ 
""d"": ""2015-01-01T00:00:00Z"", 
""n"": 32767, 
""s"": ""darkthread"",
""a"": [ 1,2,3,4,5 ]
}";
 
 
publicclass foo
        {
public DateTime d { get; set; }
publicint n { get; set; }
publicstring s { get; set; }
publicint[] a { get; set; }
        }
 
//反序列化 方法1 定義強型別物件接收資料
staticvoid lab1()
        {
            foo f = JsonConvert.DeserializeObject<foo>(jsonSrc);
            Console.WriteLine("d:{0},n:{1},s:{2},a:{3}", f.d, f.n, f.s, 
string.Join("/", f.a));
 
        }
//反序列化 方法2 使用JObject、JProperty、JArray、JToken物件
staticvoid lab2()
        {
            JObject jo = JObject.Parse(jsonSrc);
            DateTime d = jo.Property("d").Value.Value<DateTime>();
int n = jo["n"].Value<int>();
string s = jo["s"].Value<string>();
int[] ary = jo["a"].Value<JArray>()
                               .Select(o => o.Value<int>()).ToArray();
            Console.WriteLine("d:{0},n:{1},s:{2},a:{3}", d, n, s, 
string.Join("/", ary));
        }
//反序列化 方法3 使用dynamic
staticvoid lab3()
        {
            JObject jo = JObject.Parse(jsonSrc);
            dynamic dyna = jo as dynamic;
            var ary = ((JArray)jo["a"]).Cast<dynamic>().ToArray();
            Console.WriteLine("d:{0},n:{1},s:{2},a:{3}", dyna.d, dyna.n, dyna.s,
string.Join("/", ary));
        }
 
//序列化 方法1 使用強型別
staticvoid lab4()
        {
            foo f = new foo()
            {
                d = new DateTime(2015, 1, 1),
                n = 32767,
                s = "darkthread",
                a = newint[] { 1, 2, 3, 4, 5 }
            };
            Console.WriteLine("JSON:{0}", JsonConvert.SerializeObject(f));
        }
 
//序列化 方法2 使用JObject、JPorperty、JArray
staticvoid lab5()
        {
            JObject jo = new JObject();
            jo.Add(new JProperty("d", new DateTime(2015, 1, 1)));
            jo.Add(new JProperty("n", 32767));
            jo.Add(new JProperty("s", "darkthread"));
            jo.Add(new JProperty("a", new JArray(1, 2, 3, 4, 5)));
            Console.WriteLine("JSON:{0}", jo.ToString(Formatting.None));
        }
//序列化 方法3 使用dynamic
staticvoid lab6()
        {
            dynamic dyna = new JObject();
            dyna.d = new DateTime(2015, 1, 1);
            dyna.n = 32767;
            dyna.s = "darkthread";
            dyna.a = new JArray(1, 2, 3, 4, 5);
            Console.WriteLine("JSON:{0}", dyna.ToString(Formatting.None));
        }
 
    }
}

相較之下,使用dynamic動態型別,效果與使用JProperty存取相同,但程式碼簡潔許多,未來在.NET 4+環境就決定用它囉~


Viewing all articles
Browse latest Browse all 2311

Trending Articles