ASP.NET 使用 System.Web.Script.Serialization 解析 JSON (转)
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯。这些特性使JSON成为理想的数据交换语言。
JSON建构于两种结构:
1、“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表 (hash table),有键列表(keyed list),或者关联数组 (associative array)。
示例:{"UserID":11, "Name":"Froog"};
2、值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
如:
示例:var Users=[{"userID":"1","Name":"Froog","friends":["Jack","Zack","Justin"]},
{"userID":"2","Name":"Zack","friends":["Jack","Zack","Justin"]},
{"userID":"3","Name":"Justin","friends":["Jack","Zack","Justin"]}
这些都是常见的数据结构。事实上大部分现代计算机语言都以某种形式支持它们。这使得一种数据格式在同样基于这些结构的编程语言之间交号)分隔。
JSON具有以下这些形式:
对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。
数组是 值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间使用“,”(逗号)分隔值(value)可以是双引号括 起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array)。这些结构可以嵌套。
字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。
NET中通过JavaScriptSerializer类操作JSON对象
示例代码:
- JavaScriptSerializer json = new JavaScriptSerializer();
- // 反序列化JSON字符串到对象
- User user = json.Deserialize<User>(jsonString);
- // 序列化对象为JSON字符串
- string jsonString = json.Serialize(user);
JavaScriptSerializer 成员信息:http://msdn.microsoft.com/zh-cn/library /system.web.script.serialization.javascriptserializer_members.aspx
AJAX 中使用JSON
示例代码:
function getResult()
{
$.ajax({
type: "POST",
url: "?Json=true",
data:"UserInfo="+obj.toJSONString(),
success: function(msg){var obj = msg.parseJSON();
alert( "Name: " + obj.Name +",User:"+obj.User );
}
});
完整示例代码
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JsonWeb._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="http://www.json.org/json.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
// "名称/值"对的集合
var User={"userID":"1","Name":"Froog","friends":["Jack","Zack","Justin"]}
alert(User.Name);alert(User.friends[0]); // 值的有序列表
var Users=[{"userID":"1","Name":"Froog","friends":["Jack","Zack","Justin"]},
{"userID":"2","Name":"Zack","friends":["Jack","Zack","Justin"]},
{"userID":"3","Name":"Justin","friends":["Jack","Zack","Justin"]}
]
alert(Users[2].Name);alert(Users[2].friends.length);
alert(escape()); // 转换JSON字符到Object
var JsonString = '{"userID":"2","Name":"Froog","friends":["Jack","Zack","Justin"]}';
var User2 = eval('(' + JsonString + ')');
alert(User2.Name);alert(User2.friends[0]); //引用 json.js 实现JSON字符与Object相互转换。
var obj = JsonString.parseJSON();
alert(obj.toJSONString()); //AJAX 中使用JSON
function getResult()
{
$.ajax({
type: "POST",
url: "?Json=true",
data:"UserInfo="+obj.toJSONString(),
success: function(msg){
var obj = msg.parseJSON();
alert( "Name: " + obj.Name +",User:"+obj.User );
}
});
// requestHeaders: {Accept: 'application/json'} /**/,
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="AJAX" onclick="getResult()" />
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Script.Serialization;
namespace JsonWeb
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Json"] != null)
{
// AJAX 异步调用处理程序
string UserInfo = Request.Form["UserInfo"] ?? string.Empty;
JavaScriptSerializer json = new JavaScriptSerializer();
Product product = new Product() { Name = "Computer " };
if (!string.IsNullOrEmpty(UserInfo))
{
// 反序列化
User user = json.Deserialize<User>(UserInfo);
product.User = user.Name;
}
else
{
product.User = "Unknow";
}
// 序列化
string jsonString = json.Serialize(product);
// 输出异步处理结果
Response.ContentType = "application/json";
Response.Write(jsonString);
Response.End();
}
}
}
[Serializable]
public class Product
{
public string Name;
public string User;
}
public class User
{
public string Name { get; set; }
}
}
转载:征服自己,征服世界 参考C# 使用 System.Web.Script.Serialization 解析 JSON (转)
ASP.NET 使用 System.Web.Script.Serialization 解析 JSON (转)的更多相关文章
- 参考C# 使用 System.Web.Script.Serialization 解析 JSON
参考C# 使用 System.Web.Script.Serialization 解析 JSON 使用json需要引用到System.Web.Script.Serialization.习惯在解决方案右键 ...
- C# 使用 System.Web.Script.Serialization 解析 JSON
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析和生成.它基于JavaScript Programming Langu ...
- csharp: using using System.Web.Script.Serialization read json
using System; using System.Data; using System.Configuration; using System.Collections; using System. ...
- 在.net2.0下使用System.Web.Script.Serialization;
最近,在弄json字符串转为对象.需要添加这个引用System.Web.Script.Serialization;因为版本必须是dotnet2.0的原因,发现很多解决方案不适合自己.故使用这种解决办法 ...
- using System.Web.Script.Serialization
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析和生成.它基于JavaScript Programming Langu ...
- System.Web.Script.Serialization引用找不到的问题
之前在项目中要使用JavascriptSerializer这个类,需要引入System.Web.Script.Serialization命名空间,但是在添加引用中找不到这个命名空间,后来才得知Syst ...
- System.Web.Script.Serialization的引用
解决方案: 找到C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0 ==>System.Web.Extensions.d ...
- 无法将类型“ASP.login_aspx”转换为“System.Web.UI.WebControls.Login”
今天碰上了一个很傻的问题,起码我认为是这样. 项目中首页名是:Login.aspx,编译.运行都没有出现问题. 于是打包发布网站,各项内容都配置好后,问题出现了.一运行首页面就出现下面这个错误: 编译 ...
- asp.net MVC3 “System.Web.Mvc.ModelClientValidationRule”问题
错误提示: Error 1 The type 'System.Web.Mvc.ModelClientValidationRule' exists in both 'c:\Program Files ( ...
随机推荐
- SpringMVC 源码深度解析<context:component-scan>(扫描和注冊的注解Bean)
我们在SpringMVC开发项目中,有的用注解和XML配置Bean,这两种都各有自己的优势,数据源配置比較经经常使用XML配置.控制层依赖的service比較经经常使用注解等(在部署时比較不会改变的) ...
- 编写高效的Android代码
编写高效的Android代码 毫无疑问,基于Android平台的设备一定是嵌入式设备.现代的手持设备不仅仅是一部电话那么简单,它还是一个小型的手持电脑,但是,即使是最快的最高端的手持设备也远远比不上一 ...
- Dojo系列教程
Dojo学习笔记一: 认识Dojo http://blog.csdn.net/lfsfxy9/article/details/8623897 <dojo 边学边用> http://www. ...
- TP复习10
i * { padding:0; margin:0; } 居中 ## ThinkPHP 3.1.2 模板中的变量#讲师:赵桐正微博:http://weibo.com/zhaotongzheng 本节课 ...
- [ES6] 13. Using the ES6 spread operator ...
The spread operator (...) allows you to "explode" an array into its individual elements. S ...
- Swift2.0 中的String(二):基本操作
Swift中的字符串,第二篇,基本操作.其他的几篇传送门(GitHub打不开链接的同学请自行把地址github改成gitcafe,或者直接去归档里找:-P): Swift2.0 中的String(一) ...
- iOS开发——UI篇Swift篇&UIPickerView
UIPickerView //返回按钮事件 @IBAction func backButtonClick() { self.navigationController?.popViewControlle ...
- 纯css3实现的动画加载特效
之前给大家带了很多款进度加载条,今天再给大家分享一款纯css3实现的动画加载特效.效果图如下: 在线预览 源码下载 实现的代码. html代码: <div class="wrap& ...
- Golang学习 - bytes 包
------------------------------------------------------------ 对于传入 []byte 的函数,都不会修改传入的参数,返回值要么是参数的副本, ...
- 聊聊 Xcode 项目文件中的 project.pbxproj
project.pbxproj 文件被包含于 Xcode 工程文件 *.xcodeproj 之中,存储着 Xcode 工程的各项配置参数.它本质上是一种旧风格的 Property List 文件,历史 ...