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
{
static void Main(string[] args)
{
lab1();
lab2();
lab3();
lab4();
lab5();
lab6();
Console.Read();
}
static string jsonSrc =
@"{
""d"": ""2015-01-01T00:00:00Z"",
""n"": 32767,
""s"": ""darkthread"",
""a"": [ 1,2,3,4,5 ]
}";
public class foo
{
public DateTime d { get; set; }
public int n { get; set; }
public string s { get; set; }
public int[] a { get; set; }
}
//反序列化 方法1 定義強型別物件接收資料
static void 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物件
static void 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
static void 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 使用強型別
static void lab4()
{
foo f = new foo()
{
d = new DateTime(2015, 1, 1),
n = 32767,
s = "darkthread",
a = new int[] { 1, 2, 3, 4, 5 }
};
Console.WriteLine("JSON:{0}", JsonConvert.SerializeObject(f));
}
//序列化 方法2 使用JObject、JPorperty、JArray
static void 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
static void 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));
}
}
}