.net处理JSON简明教程

Json.Net是.net中的一种流行的高性能的JSON框架。

特点

  1. 灵活的JSON序列化转化.net对象为JSON字符串。和把JSON字符串转换为.net对象。
  2. 手动读写JSON的Linq to JSON
  3. 比.net内置的JSON序列化程序更高的性能和速度。
  4. 便于读写的JSON
  5. 从XML中读取或写入JSON
  6. 支持Silverlight和Windows phone.

    当你读写的JSON与.net类紧密关联时,JSON序列化程序是一个不错的选择。JSON序列化程序将自动读写相关类的JSON。

    如果你只对JSON里面的数据感兴趣、你没有与JSON相关联的.net类或者JSON数据与你的类没有任何关系,你需要从对象中手动读写数据。以上各种情况下,你可以使用LINQ To JSON. LINQ To JSON 允许你在.net中更容易的读取、写入、修改JSON数据。

    Download Json.NET from CodePlex or install using NuGet。

    PM> Install-Package Newtonsoft.Json

    JSON.net下载地址列表

    http://json.codeplex.com/releases/view/74287

    提供JSON.NET 4.0 Release 3版本地址

    http://json.codeplex.com/releases/view/74287#DownloadId=287841

    更多JSON详细信息,请查看: http://james.newtonking.com/projects/json-net.aspx

    先构造一个简单的类employee

    Public class employee{

    Public string eid{get;set;}

    Public string ename{get;set;}

    Public string esex{get;set;}

    Public datetime birthday{get;set;}

    }

    JSON序列化与反序列化的方案

    1. 使用Json.Net 处理JSON序列化与反序列化

序列化方法

private string JsonSerialize(employee emp) {

return Newtonsoft.Json.JsonConvert.SerializeObject(emp);

}

反序列化方法

private employee JsonDeserialize(string json) {

return (employee)(Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(employee)));

}

  1. 使用JavaScriptSerializer进行序列化、反序列化

    序列化方法

private string JsonSerialize (employee emp) {

return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(emp);

}

反序列化

Private string JsonDeserialize (string json){

return (employee)(newSystem.Web.Script.Serialization.JavaScriptSerializer().Deserialize(json,typeof(employee)));

}

  1. 通过类DataContractJsonSerializer对JSON序列化和反序列化

    序列化方法

private string JsonSerialize (employee emp) {

System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = newSystem.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee));

System.IO.MemoryStream ms = new System.IO.MemoryStream();

dcjs.WriteObject(ms, emp);

string json = System.Text.Encoding.UTF8.GetString(ms.ToArray());

ms.Close();

return json;

}

反序列化方法

private employee JsonDeserialize (string json) {

System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = newSystem.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee));

System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));

employee obj = (employee)(dcjs.ReadObject(ms));

return obj;

}

  1. 通过Newtonsoft.Json.Linq.JObject获取JSON数据

private void LinqJson(string json) {

JObject obj = Newtonsoft.Json.Linq.JObject.Parse(json);

//获取全部数据值

foreach (JToken token in obj.Values()) {

Response.Write(token.ToString());

}

//获取唯一值

Response.Write(obj["eid"].ToString()+"<br />"); }

  1. 5、LINQ to JSON Example

string json = @"{

""Name"": ""Apple"",

""Expiry"": new Date(1230422400000),

""Price"": 3.99,

""Sizes"": [

""Small"",

""Medium"",

""Large""

]

}";

JObject o = JObject.Parse(json);

string name = (string)o["Name"];

// Apple

JArray sizes = (JArray)o["Sizes"];

string smallest = (string)sizes[0];

JSON序列化和反序列化日期时间的处理

JSON格式不直接支持日期和时间。DateTime值值显示为"/Date(700000+0500)/"形式的JSON字符串,其中第一个数字(在提 供的示例中为 700000)是 GMT 时区中自 1970年 1 月 1 日午夜以来按正常时间(非夏令时)经过的毫秒数。该数字可以是负数,以表示之前的时间。示例中包括"+0500"的部分可选,它指示该时间属于Local 类型,即它在反序列化时应转换为本地时区。如果没有该部分,则会将时间反序列化为Utc。

使用DataContractJsonSerializer的序列化方式对日期格式进行处理,其他的(反)序列化方案的使用方式是相同的。设计思想是通过正则表达式匹配,替换JSON里面的日期数据为正常的日期格式。

序列化方法

private string JsonSerialize (employee emp) {

System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = newSystem.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee));

System.IO.MemoryStream ms = new System.IO.MemoryStream();

dcjs.WriteObject(ms, emp);

string json = System.Text.Encoding.UTF8.GetString(ms.ToArray());

ms.Close();

//替换JSON时间为字符串

string p = @"\\/Date\((\d+)\)\\/";

System.Text.RegularExpressions.MatchEvaluator me = newSystem.Text.RegularExpressions.MatchEvaluator(ConvertJsonDateToDataString);

System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(p);

json = regex.Replace(json, me);

return json;

}

private string ConvertJsonDateToDataString(System.Text.RegularExpressions.Match m) {

string result = string.Empty;

DateTime dt = new DateTime(1970,1,1);

dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));

dt = dt.ToLocalTime();

result = dt.ToString("yyyy-MM-dd HH:mm:ss");

return result;

}

反序列化方法

private employee JsonDeserialize (string json)

{

string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";

System.Text.RegularExpressions.MatchEvaluator me = newSystem.Text.RegularExpressions.MatchEvaluator(ConvertDateStringToJsonDate);

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(p);

json = reg.Replace(json, me);

System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs=newSystem.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee));

System.IO.MemoryStream ms=new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));

employee emp=(employee)dcjs.ReadObject(ms);

return emp;

}

private string ConvertDateStringToJsonDate(System.Text.RegularExpressions.Match m)

{

string result = string.Empty;

DateTime dt = DateTime.Parse(m.Groups[0].Value);

dt = dt.ToUniversalTime();

TimeSpan ts = dt - DateTime.Parse("1970-1-1");

result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);

return result;

}

转载地址:http://wenqingluomo.blog.163.com/blog/static/7917174020111035956910/

.net处理JSON简明教程的更多相关文章

  1. appium简明教程

    appium简明教程 什么是appium? 下面这段介绍来自于appium的官网. Appium is an open-source tool you can use to automate mobi ...

  2. OAuth 白话简明教程 3.客户端模式(Client Credentials)

    转自:http://www.cftea.com/c/2016/11/6704.asp OAuth 白话简明教程 1.简述 OAuth 白话简明教程 2.授权码模式(Authorization Code ...

  3. Node.js学习笔记(3):NPM简明教程

    Node.js学习笔记(3):NPM简明教程 NPM常用操作 更新NPM版本 npm install npm -g -g,表示全局安装.我们可以指定更新版本,只需要在后面填上@版本号即可,也可以输入@ ...

  4. React-Router 中文简明教程(上)

    概述 说起 前端路由,如果你用过前端 MV* 框架构建 SPA 应用(单页面应用),对此一定不陌生. 传统开发中的 路由,是由服务端根据不同的用户请求地址 URL,返回不同内容的页面,而前端路由则将这 ...

  5. nacos、ribbon和feign的简明教程

    nacos简明教程 为什么需要nacos? 在微服务架构中,微服务之间经常要相互通信和调用,而且一个服务往往存在多个实例来降低负荷或保证高可用.我们假定A服务要调用B服务,最简单的方式把B服务的地址和 ...

  6. 2013 duilib入门简明教程 -- 第一个程序 Hello World(3)

    小伙伴们有点迫不及待了么,来看一看Hello World吧: 新建一个空的win32项目,新建一个main.cpp文件,将以下代码复制进去: #include <windows.h> #i ...

  7. 2013 duilib入门简明教程 -- 部分bug (11)

     一.WindowImplBase的bug     在第8个教程[2013 duilib入门简明教程 -- 完整的自绘标题栏(8)]中,可以发现窗口最大化之后有两个问题,     1.最大化按钮的样式 ...

  8. 2013 duilib入门简明教程 -- 部分bug 2 (14)

        上一个教程中提到了ActiveX的Bug,即如果主窗口直接用变量生成,则关闭窗口时会产生崩溃            如果用new的方式生成,则不会崩溃,所以给出一个临时的快速解决方案,即主窗口 ...

  9. 2013 duilib入门简明教程 -- 自绘控件 (15)

        在[2013 duilib入门简明教程 -- 复杂控件介绍 (13)]中虽然介绍了界面设计器上的所有控件,但是还有一些控件并没有被放到界面设计器上,还有一些常用控件duilib并没有提供(比如 ...

随机推荐

  1. 【LeetCode】223 - Rectangle Area

    Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined b ...

  2. Chapter6:函数

    执行函数的第一步是(隐式地)定义并初始化它的形参.所以,函数最外层作用域中的局部变量也不能使用与函数形参一样的名字. 局部静态变量:在程序的执行路径第一次经过对象定义语句时初始化,并且直到程序终止才被 ...

  3. 朝鲜RedStar_OS_3.0安装图解

    前天exploit-db上出现了3个Local Exploit,都是来自朝鲜的RedStar 3.0的vul.网上也下到了镜像,按网上的方法测试了下,真的是 ————————————————————— ...

  4. Pregel: A System for Large-Scale Graph Processing(译)

    [说明:Pregel这篇是发表在2010年的SIGMOD上,Pregel这个名称是为了纪念欧拉,在他提出的格尼斯堡七桥问题中,那些桥所在的河就叫Pregel.最初是为了解决PageRank计算问题,由 ...

  5. Spring MVC 问题列表:目录

    学习SpringMVC时遇到不少问题,这里将其汇总. 1.怎么搭建SpringMVC 2.SpringMVC和Spring使用是配置到一个文件中还是两个配置文件 3.SpringMVC接受从前台请求 ...

  6. leetcode@ [273] Integer to English Words (String & Math)

    https://leetcode.com/problems/integer-to-english-words/ Convert a non-negative integer to its englis ...

  7. flex编译命令相关

    最近碰到几次flex组件集版本问题,mx容器包含s组件,错误百出,会一直提示皮肤文件错误,上网查了一下,只要在工程属性中--->Flex编译器--->附加的编译参数中加入如下命令行即可:- ...

  8. Codeforces Round #367 (Div. 2) D. Vasiliy's Multiset (0/1-Trie树)

    Vasiliy's Multiset 题目链接: http://codeforces.com/contest/706/problem/D Description Author has gone out ...

  9. GRUB加密

    在 /etc/grub.conf 内添加password=密码(也可使用加密的密码password= --md5 加密过的密码) 如何获得加密密码? 那就是grub-md5-crypt命令 简单流程如 ...

  10. to_number,Extract oracle的关键字

    to_number(Extract(year from 字段名)) 简介:获取时间字段的年份后转换为数字