您的位置:首页 > Web前端 > JavaScript

JSON使用Linq序列化与反序列化.NET类型

2015-12-15 08:20 459 查看
一、使用Linq序列化
1.先创建一个Post对象

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JSONDemo
{
public class Post
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public IList<string> Categories { get; set; }
public DateTime? PostedDate { get; set; }
public string Html { get; set; }
}
}


2.再把Post置于列表中,然后实例化此对象。再实例化一个JArray对象,使用Linq把查询到的数据赋值到此对象中。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web;
using GongHuiNewtonsoft.Json.Linq;

namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
IList<Post> list = new List<Post>
{
new Post
{
Title="JSONDemo",
PostedDate=DateTime.Now,
Link="http://blog.csdn.net/lovegonghui/article/details/50310153",
Description="这是使用Linq序列化JSON",
Html=@"<h3>Title!</h3><p>Content!</p>"
}
};

JArray array=new JArray(
list.Select(p=>new JObject
{
{"Title",p.Title},
{
"Content",new JObject
{
{"Link",p.Link},
{"Description",p.Description}
}
},
{"PostedDate",p.PostedDate},
{"Html",HttpUtility.HtmlEncode(p.Html)},
})
);

Console.WriteLine(array.ToString());
}
}
}


3.运行的结果



二、使用Linq反序列化
1.先创建一个json字符串,用转换成JArray数组,然后创建一个Post对象.把这个对象添加到List列表中.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web;
using GongHuiNewtonsoft.Json.Linq;

namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
string json= @"[
{
'Title':'JSONDemo',
'PostedDate':'2015-12-14 17:02:33',
'Html':'<h3>Title!</h3>\r\n<p>Content!</p>'
}
]";

JArray array = JArray.Parse(json);

IList<Post> list = array.Select(p => new Post
{
Title = (string)p["Title"],
PostedDate = (DateTime)p["PostedDate"],
Html =HttpUtility.HtmlDecode( (string)p["Html"])
}).ToList();

Console.WriteLine(list[0].Title);
Console.WriteLine(list[0].Html);
Console.WriteLine(list[0].PostedDate);
Console.WriteLine(list[0].Link);
}
}
}


2.反序列化的结果



JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: