惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
C
Check Point Blog
J
Java Code Geeks
腾讯CDC
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 三生石上(FineUI控件)
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
罗磊的独立博客
Last Week in AI
Last Week in AI
B
Blog
IT之家
IT之家
S
SegmentFault 最新的问题
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
博客园 - 聂微东
U
Unit 42
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
MyScale Blog
MyScale Blog

博客园 - 举重-若轻

Survey 2遍的解决办法 Error occurred in deployment step 'Activate Features': Feature with Id 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' is not installed in this farm using powershell to change the some sub-webs' system master page AssetUrlSelector export to excel 用powershell更新user profile service中的一个字段 create a 全局临时表 Generate a random integrater Remote Debugging GAC'd Assemblies in SharePoint get all user profiles redirecting to custom user profile page css的em概念 异步调用的一个例子 .NET种Json时对单引号和特殊字符串的处理 CSS备忘 SharePoint 资料 Server.MapPath方法的应用方法 jquery 参考材料 备忘 用powershell更新user的display name
JSON的客户端和服务器操作
举重-若轻 · 2012-09-16 · via 博客园 - 举重-若轻

首先感谢Hunt. C的资料,本文主要引用了他的内容(http://www.cnblogs.com/hunts/archive/2006/11/20/566694.aspx

http://www.cnblogs.com/hunts/archive/2006/11/20/566694.html

1. 了解JSON 

http://www.json.org 

2. 客户端(如web 网页)操作

客户端操作就是把字符串处理成一个JSON对象或者进行相反操作,这么做是因为服务器端往客户端传递的是一个字符串,比如:{"Employees":[{"ID":"1","Name":"Shuang Er"},{"ID":"2","Name":"Tai Ping Princess"}]} (韦小宝的2个老婆),客户端收到这个字符串以后,需要处理成一个JavaScript对象,从而能进一步使用,比如拼合成HTML显示出来。

一般来说最好借助一个JavaScript类库来处理字符串和JSON/JavaScript对象之间的转换, 我这里用的是https://github.com/douglascrockford/JSON-js,只需要下载和引用json2.js即可 

字符串到JSON/JavaScript对象:

var employeeInString =  '{"Employees":[{"ID":"1","Name":"ShuangEr"},{"ID":"2","Name":"TaiPing princess"}]} ';

var employeesObject = JSON.parse(employeeInString);

然后可以使用 employees对象了,比如employeesObject.employees[0].Name

(用eval()方法是可以替换parse方法的,但是eval方法有安全性问题,如果数据是用户数据的尽量不要用它。)

JSON/JavaScript对象到字符串:

var employeeInString = JSON.stringify(employees);


需要注意的是,如果是用jquery.ajax方法,jquery会根据服务器端返回contenttype的值自动把返回值转换成json对象。

 3. 服务器端操作:

这里推荐用这个类库来进行C#对象和JSON 字符串之间的转换: http://json.codeplex.com/releases/view/94220 

假设有个Employee类:

public class Employee     { 

        public int ID {get;set;}         public string Name {get;set;}

}

C#对象到JSON格式的String:

Employee employee = new Employee();             

employee.ID = 1;

employee.Name = "shuang er";  

string employeeInJSONString = JsonConvert.SerializeObject(employee);

employeeInJSONString的值为:{"ID":1,"Name":"shuang er"}

往回转化就更简单了:

Employee deserializedEmployee = (Employee)JsonConvert.DeserializeObject(

employeeInJSONStringtypeof(Employee));