JSON使用Linq序列化与反序列化.NET类型
2015-12-15 08:20
459 查看
一、使用Linq序列化
1.先创建一个Post对象
2.再把Post置于列表中,然后实例化此对象。再实例化一个JArray对象,使用Linq把查询到的数据赋值到此对象中。
3.运行的结果
二、使用Linq反序列化
1.先创建一个json字符串,用转换成JArray数组,然后创建一个Post对象.把这个对象添加到List列表中.
2.反序列化的结果
JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751
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
相关文章推荐
- Common JS String Methods
- action 交互到带命名空间的action 还有返回的jsp
- 通过javascript在网页端解压zip文件并查看压缩包内容
- javascript脚本从载入浏览器到显示执行的过程解析
- js----创建节点和插入节点
- JSP自定义标签入门学习
- 理解javascript闭包
- js简单网速测试方法完整实例
- JavaScript获取当前cpu使用率的方法
- JavaScript为事件句柄绑定监听函数实例详解
- JavaScript组件开发完整示例
- JavaScript中Textarea滚动条不能拖动的解决方法
- js判断手机访问或者PC的几个例子(常用于手机跳转)
- javascript实现网页端解压并查看zip文件
- js编写“贪吃蛇”的小游戏
- javascript实现html页面之间参数传递的四种方法实例分析
- Javascript基于AJAX回调函数传递参数实例分析
- 轻松学习Javascript闭包函数
- 浅析javascript的return语句
- js函数区分数组和对象