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

推荐订阅源

量子位
F
Fortinet All Blogs
J
Java Code Geeks
Y
Y Combinator Blog
Stack Overflow Blog
Stack Overflow Blog
V
Visual Studio Blog
M
MIT News - Artificial intelligence
腾讯CDC
Last Week in AI
Last Week in AI
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Jina AI
Jina AI
Microsoft Security Blog
Microsoft Security Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Proofpoint News Feed
博客园 - 叶小钗
Recent Announcements
Recent Announcements
T
Tailwind CSS Blog
Engineering at Meta
Engineering at Meta
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
L
LangChain Blog
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

博客园 - 举重-若轻

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));