org.json put 和json value appendd的区别

Uses of Class org.activiti.engine.impl.util.json.JSONArray (Activiti - Engine 5.16 API) - Javadoc Extreme
JavaScript is disabled on your browser.Packages that use  PackageDescription Uses of
in Methods in
that return  Modifier and TypeMethod and DescriptionJSONArray.(int index)Get the JSONArray associated with an index.JSONObject.( key)Get the JSONArray value associated with a key.JSONObject.()Produce a JSONArray containing the names of the elements of this JSONObject.JSONArray.(int index)Get the optional JSONArray associated with an index.JSONObject.( key)Get an optional JSONArray associated with a key.JSONArray.(boolean value)Append a boolean value.JSONArray.( value)Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection.JSONArray.(double value)Append a double value.JSONArray.(int value)Append an int value.JSONArray.(int index,
boolean value)Put or replace a boolean value in the JSONArray.JSONArray.(int index,
 value)Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection.JSONArray.(int index,
double value)Put or replace a double value.JSONArray.(int index,
int value)Put or replace an int value.JSONArray.(int index,
long value)Put or replace a long value.JSONArray.(int index,
 value)Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map.JSONArray.(int index,
 value)Put or replace an object value in the JSONArray.JSONArray.(long value)Append an long value.JSONArray.( value)Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map.JSONArray.( value)Append an object value.static CDL.( x)Produce a JSONArray of strings from a row of comma delimited values.JSONObject.( names)Produce a JSONArray containing the values of the members of this JSONObject.static CDL.( names,
 x)Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of element names.static CDL.( names,
 string)Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of element names.static CDL.( x)Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names.static JSONML.( string)Convert a well-formed (but not necessarily valid) XML string into a JSONArray using the JsonML transform.static CDL.( string)Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names.static JSONML.( x)Convert a well-formed (but not necessarily valid) XML string into a JSONArray using the JsonML transform.Methods in
with parameters of type  Modifier and TypeMethod and Descriptionstatic CDL.( names,
 x)Produce a JSONObject from a row of comma delimited text, using a parallel JSONArray of strings to provides the names of the elements.static CDL.( ja)Produce a comma delimited text row from a JSONArray.JSONObject.( names)Produce a JSONArray containing the values of the members of this JSONObject.static CDL.( names,
 x)Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of element names.static CDL.( names,
 string)Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of element names.JSONArray.( names)Produce a JSONObject by combining a JSONArray of names with the values of this JSONArray.static JSONML.( ja)Reverse the JSONML transformation, making an XML text from a JSONArray.static CDL.( ja)Produce a comma delimited text from a JSONArray of JSONObjects.static CDL.( names,
 ja)Produce a comma delimited text from a JSONArray of JSONObjects using a provided list of names.Copyright © 2014 . All rights reserved.
Related Articles
Add the Maven Dependecy to your project:
New Blog Post!
Astyanax, the Cassandra Java library
New blog post: Getting started with Astyanax, the open source Cassandra java library and connect your application to one of the most important NoSQL database.Ajax与JSON的一些学习总结
字体:[ ] 类型:转载 时间:
Ajax技术的核心是XMLHttpRequest对象(简称XHR),可以通过使用XHR对象获取到服务器的数据,然后再通过DOM将数据插入到页面中呈现。虽然名字中包含XML,但Ajax通讯与数据格式无关,所以我们的数据格式可以是XML或JSON等格式
1.1.1 摘要 Ajax技术的核心是XMLHttpRequest对象(简称XHR),可以通过使用XHR对象获取到服务器的数据,然后再通过DOM将数据插入到页面中呈现。虽然名字中包含XML,但Ajax通讯与数据格式无关,所以我们的数据格式可以是XML或JSON等格式。 XMLHttpRequest对象用于在后台与服务器交换数据,具体作用如下: 在不重新加载页面的情况下更新网页 在页面已加载后从服务器请求数据 在页面已加载后从服务器接收数据 在后台向服务器发送数据 1.1.2 正文 XMLHttpRequest是一个JavaScript对象,它是由微软设计,并且被Mozilla、Apple和Google采纳,W3C正在标准化它。它提供了一种简单的方法来检索URL中的数据。 我们要创建一个XMLHttpRequest实例,只需new一个就OK了:
代码如下: //// Creates a XMLHttpRequest object. var req = new XMLHttpRequest();
也许有人会说:“这可不行啊!IE6不支持原始的XHR对象”,确实是这样,我们在后面将会介绍支持IE6或更老版本创建XHR对象的方法。 XMLHttpRequest的用法 在创建XHR对象后,接着我们要调用一个初始化方法open(),它接受五个参数具体定义如下:
代码如下: void open( DOMString method, //"GET", "POST", "PUT", "DELETE" DOMString url, optional boolean async, optional DOMString user, optional DOMString password );
通过上面的定义我们知道open()方法的签名包含五个参数,其中有参数method和url地址是必填的,假设我们针对URL: myxhrtest.aspx发送GET请求获取数据,具体定义如下:
代码如下: var req = new XMLHttpRequest(); req.open( "GET", "myxhrtest.aspx", false );
通过上述代码会启动一个针对myxhrtest.aspx的GET请求,这里有两点要注意:一是URL相对于执行代码的当前页面(使用绝对路径);二是调用open()方法并不会真正发送请求,而只是启动一个请求准备发送。 只能向同一个域中使用相同端口和协议的URL中发送请求;如果URL与启动请求的页面有任何差别,都会引发安全错误。 要真正发送请求要使用send()方法,send()方法接受一个参数,即要作为请求主体发送的数据,如果不需要通过请求主体发送数据,我们必须传递一个null值。在调用send()之后,请求就会被分派到服务器,完整Ajax请求代码如下:
代码如下: var req = new XMLHttpRequest(); req.open( "GET", "myxhrtest.aspx", false ); req.send(null);
在发送请求之后,我们需要检查请求是否执行成功,首先可以通过status属性判断,一般来说,可以将HTTP状态代码为200作为成功标志。这时,响应主体内容会保存到responseText中。此外,状态代码为304表示请求的资源并没有被修改,可以直接使用浏览器缓存的数据,Ajax的同步请求代码如下:
代码如下: if (req != null) { req.onreadystatechange = function() { if ((req.status &= 200 && req.status & 300) || req.status == 304) { //// Do something. } else { alert("Request was unsuccessful: " + req.status); } }; req.open("GET", "www.myxhrtest.aspx", true); req.send(null); }
前面我们定义了Ajax的同步请求,如果我们发送异步请求,那么在请求过程中javascript代码会继续执行,这时可以通过readyState属性判断请求的状态,当readyState = 4时,表示收到全部响应数据,属性值的定义如下:
readyState值
未初始化;尚未调用open()方法
启动;尚未调用send()方法
已发送;但尚未收到响应
接收;已经收到部分响应数据
完成;收到全部响应数据表1 readyState属性值 同步请求:发生请求后,要等待服务器执行完毕才继续执行当前代码。 异步请求:发生请求后,无需等到服务器执行完毕,可以继续执行当前代码。 现在我们要增加判断readyState属性值,当readyState = 4时,表示全部数据接收完成, 所以Ajax的异步请求代码如下:
代码如下: if (req != null) { req.onreadystatechange = function() { //// Checks the asyn request completed or not. if (req.readyState == 4) { if ((req.status &= 200 && req.status & 300) || req.status == 304) { //// Do something. } else { alert("Request was unsuccessful: " + req.status); } } }; req.open("GET", "www.myxhrtest.aspx", true); req.send(null); }
Ajax同源请求 现在我们对Ajax的请求实现有了初步的了解,接下来我们将通过具体的例子说明Ajax请求的应用场合和局限。 在日常网络生活中,我们在浏览器的地址中输入要访问的URL并且回车,浏览器会向服务器发送请求,当服务器收到请求后,把相应的请求页面发送回浏览器,我们会发现页面大部分加载完毕,有些还没有加载完毕。总得来说,采用异步加载方式不会影响已加载完毕的页面浏览,我们可以通过Ajax实现异步加载。 这里我们以AdventureWorks数据库为例,把产品表(Product)中的数据通过报表呈现给用户,我们可以通过多种方法实现该报表需求,这里我们将通过Ajax实现该功能。 首先,我们要把后台数据转换为JSON格式,接下来我们定义Product表的数据库访问对象(DAO),具体的实现代码如下:
代码如下: /// &summary& /// The product datatable dao. /// &/summary& public class ProductDao { /// &summary& /// Initializes a new instance of the &see cref="ProductDao"/& class. /// &/summary& public ProductDao() { } /// &summary& /// Gets or sets the product id. /// &/summary& public int Id { } /// &summary& /// Gets or sets the product name. /// &/summary& public string Name { } /// &summary& /// Gets or sets the product serial number. /// &/summary& public string SerialNumber { } /// &summary& /// Gets or sets the product qty. /// &/summary& public short Qty { } }
前面我们定义了Product表的数据库访问对象——ProductDao,它包含四个属性分别是产品的Id,名称,序列号和销售数量。 接下来,让我们实现Product表的数据库操作类。
代码如下: /// &summary& /// Product table data access manager. /// &/summary& public class ProductManager { /// &summary& /// The query sql. /// &/summary& private const string Query = "SELECT ProductID, Name, ProductNumber, SafetyStockLevel FROM Production.Product"; /// &summary& /// Stores the object of &see cref="ProductDao"/& into list. /// &/summary& private IList&ProductDao& _products = new List&ProductDao&(); /// &summary& /// Gets all products in product table. /// &/summary& /// &returns& /// The list of &see cref="ProductDao"/& object. /// &/returns& public IList&ProductDao& GetAllProducts() { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLCONN"].ToString())) using (var com = new SqlCommand(Query, con)) { con.Open(); using (var reader = com.ExecuteReader(CommandBehavior.CloseConnection)) { while (reader.Read()) { var product = new ProductDao { Id = (int)reader["ProductID"], Name = (string)reader["Name"], SerialNumber = (string)reader["ProductNumber"], Qty = (short)reader["SafetyStockLevel"] }; _products.Add(product); } } } return _ } }
前面我们实现了Product表的数据库操作类——ProductManager,它包含两个私有字段Quey和_products,还有一个获取Product表中数据的方法——GetAllProducts()。 通过实现ProductDao和ProductManager,而且我们提供GetAllProducts()方法,获取Product表中的数据,接下来我们要调用该方法获取数据。 为了使数据通过JSON格式传递给页面,这里我们要创建一般处理程序(ASHX文件), 一般处理程序适用场合: 创建动态图片 返回REST风格的XML或JSON数据 自定义HTML
图1一般处理程序 把一般处理程序文件添加到项目中时,会添加一个扩展名为.ashx的文件,现在我们创建一个一般处理程序ProductInfo,具体代码如下:
代码如下: &%@ WebHandler Language="C#" Class="ProductInfo" %& using System.Runtime.Serialization.J using System.W using ASP.App_C /// &summary& /// The product data handler. /// &/summary& public class ProductInfo : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "application/json"; // Creates a &see cref="ProductManager"/& oject. var manager = new ProductManager(); // Invokes the GetAllProducts method. var products = manager.GetAllProducts(); // Serializes data to json format. var json = new DataContractJsonSerializer(products.GetType()); json.WriteObject(context.Response.OutputStream, products); } // Whether can resuable by other handler or not. public bool IsReusable { get {
大家注意到ProductInfo类实现了IHttpHandler接口,该接口包含一个方法ProcessRequest()方法和一个属性IsReusable。ProcessRequest()方法用于处理入站的Http请求。在默认情况下,ProductInfo类会把内容类型改为application/json,然后我们把数据通过JSON格式写入输入流中;IsReusable属性表示相同的处理程序是否可以用于多个请求,这里我们设置为false,如果为了提高性能也可以设置为true。 如下图所示,我们通过ProductInfo类成功地实现获取数据到响应流中,并且以JSON格式显示出来。
图2 Http请求 当我们请求ProductInfo时, 首先它会调用ProcessRequest()方法,接着调用GetAllProducts()方法从数据库中获取数据,然后把数据通过JSON格式写入到响应流中。 现在,我们已经成功地把数据通过JSON格式写入到响应流当中,接着我们将通过Ajax方式请求数据并且把数据显示到页面中。 首先,我们定义方法createXHR()用来创建XMLHttpRequest对象,前面我们提到IE6或者更老的版本不支持XMLHttpRequest()方法来创建XMLHttpRequest对象,所以我们要在createXHR()方法中,增加判断当前浏览器是否IE6或更老的版本,如果是,就要通过MSXML库的一个ActiveX对象实现。因此,在IE中可能遇到三种不同版本的XHR对象(MSXML2.XMLHttp6.0,MSXML2.XMLHttp3.0和MSXML2.XMLHttp)。
代码如下: // Creates a XMLHttpRequest object bases on web broswer. function createXHR() { // Checks whether support XMLHttpRequest or not. if (typeof XMLHttpRequest != "undefined") { return new XMLHttpRequest(); } // IE6 and elder version. else if (typeof ActiveXObject != "undefined") { if (typeof arguments.callee.activeXString != "string") { var versions = [ "MSXML2.XMLHttp6.0", "MSXML2.XMLHttp3.0", "MSXML2.XMLHttp"]; for (var i = 0; i & versions. i++) { try { var xhr = new ActiveXObject(versions[i]); arguments.callee.activeXString = versions[i];
} catch (ex) { throw new Error(ex.toString()); } } return new ActiveXObject(arguments.callee.activeXString); } else { throw new Error("No XHR object available"); } }
} $(document).ready(function() { GetDataFromServer(); });
前面我们定义了一个比较通用的方法用来创建XMLHttpRequest对象,并且它支持IE6或更老版本创建XMLHttpRequest对象,接下来我们将通过Ajax方法请求数据。
代码如下: function GetDataFromServer() { // Creates a XMLHttpRequest object. var req = new createXHR(); if (req != null) { req.onreadystatechange = function() { if (req.readyState == 4) { if ((req.status &= 200 && req.status & 300) || req.status == 304) { ////alert(req.responseText); var jsonTextDiv = document.getElementById("jsonText"); // Deserializes JavaScript Object Notation (JSON) text to produce a JavaScript value. var data = JSON.parse(req.responseText); for (var i = 0; i & data. i++) { var item = data[i]; var div = document.createElement("div"); div.setAttribute("class", "dataItem"); // Inserts data into the html. div.innerHTML = item.Name + " sold " + item.Qty + "; Product number: " + item.SerialN jsonTextDiv.appendChild(div); } } else { alert("Request was unsuccessful: " + req.status); } } }; // Sends a asyn request. req.open("GET", "ProductInfo.ashx", true); req.send(null); } }
由于前面我们介绍过Ajax发生请求的方法,所以不再重复介绍了,但我们注意到GetDataFromServer()方法中,获取responseText数据(JSON格式),然后通过parse()方法把JSON格式数据转换为Javascript对象,最后把数据插入到div中,页面呈现效果如下:
图3 Ajax请求结果 现在,我们成功地把数据输出到页面当中,也许用户还会觉得用户体验不好,那么我们给就该页面增加CSS样式。 由于时间的关系,我们已经把CSS样式定义好了,具体如下:
代码如下: #header { width: 100%; margin-left: 10 margin-right: 10 background-color:#480082; color: #FFFFFF; } body { margin-left: 40 margin-right: 40 } div#jsonText { background-color: #d9d9d9; -webkit-border-radius: 6 border-radius: 6 margin: 10px 0px 0px 0 padding: 0 border: 1px solid #d9d9d9; } div.dataItem { font-family: Verdana, Helvetica, sans- color: #434343; padding: 10 } div.dataItem:nth-child(2n) { background-color: # } div.dataItem:first-child { -webkit-border-top-left-radius: 6 -webkit-border-top-right-radius: 6 border-top-left-radius: 6 border-top-right-radius: 6 } div.dataItem:last-child { -webkit-border-bottom-left-radius: 6 -webkit-border-bottom-right-radius: 6 border-bottom-left-radius: 6 border-bottom-right-radius: 6 }
我们刷新一下页面,OK现在页面效果好多了。
图4 Ajax请求结果 同源策略与跨源策略 上面我们获取页面和数据都是在同源请求情况下,也就是说,客户端浏览器请求的页面和数据都是属于同一域名、同一端口和同协议。 同源策略:阻止从一个域上加载的脚本获取或操作另一个域上的文档属性。也就是说,受到请求的URL的域必须与当前Web页面的域相同、相同端口。这意味着浏览器隔离来自不同源的内容,以防止它们之间的操作。
图5同源请求过程 在一些情况下,我们不可以避免地要地需要从其他域名或服务器中跨域请求数据,但前面提到Ajax只能向同一个域中使用相同端口和协议的URL中发送请求;如果URL与启动请求的页面有任何差别,都会引发安全错误。 跨源策略(CORS):是一个Web浏览器技术规范,它定义了一个方法让Web服务器允许其他域名页面访问它的资源。跨源策略定义了一个方法让浏览器和服务器可以交互决定是否允许跨源请求。
图6跨源请求过程 大家注意到同源请求中我们使用的是JSON格式,但在跨源请求中却是使用JSONP,这时大家可能有点困惑,坦然我刚开始学习的时候也是这样的。 首先我们必须理解JSON和JSONP的区别:JSON是一种数据格式,而JSONP像是通过一个方法名来封装JSON格式;由于浏览器允许跨源请求&script&资源,如我们的HTML页面代码中使用了Google的jQuery库,当我们Web程序发送跨源请求后,服务器给我们提供响应数据,但服务器无法预知接受JSON数据的方法名,所以我们要提供一个方法名。 Ajax跨源请求 跨域请求数据解决方案主要有如下解决方法: JSONP方式 表单POST方式 服务器代理 Html5的XDomainRequest Flash request 在介绍JSONP方式解决跨域请求数据之前,首先我们看看JSONP的定义。 JSONP(JSON with Padding)是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过Javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实现形式)。 由于同源策略的限制,XMLHttpRequest只允许请求当前源(域名、协议、端口)的资源,为了实现跨域请求,可以通过script标签实现跨域请求,然后在服务端输出JSON数据并执行回调函数,从而解决了跨域的数据请求。 假设博客园提供一个API接口:/hotblogs/json?,供开发者调用获取热门博文。 这里我们可以通过两种方式调用该接口: 1. 用Javascript定义回调函数 其实,通过Javascript定义回调函数调用该接口比较直观,我们只需告诉服务器接收数据的方法名就OK了,比如: /hotblogs/json? callback=myFunction 其中myFunction是我们在页面自定义的函数用来接收服务器回传的数据,myFunction的定义如下:
代码如下: // The call back function. function myFunction(data) { // Your code here. }
2. 使用jQuery的Ajax方法 假设我们想在博客中增加显示浪微博的公共微博信息,我们可以在博客中调用微博提供的API获取跨源数据,接下来,我们将使用jQuery的Ajax方法获取跨域数据。 首先,查看微博API文档找到了公共微博的API接口statuses/public_timeline 获取最新的公共微博消息,它支持JSON或XML格式数据。
类型及范围
申请应用时分配的AppKey,调用接口时候代表应用的唯一身份。(采用OAuth授权方式不需要此参数)
int,缺省值20,最大值200
每次返回的记录数
int,缺省值20,最大值200
每次返回的记录数表2请求参数 上面的请求参数只有source(AppKey)是必须的,所以我们需要向微博申请AppKey,在调用API时,只需把我们的AppKey传递给接口就OK了。 接下来让我们看一下微博数据组成,这里我们使用JSON viewer查看微博的数据组成,具体数据如下:
图7微博JSON数据 通过上图,我们知道微博的数据信息很丰富,它是由一些基础数据类型和复杂数据类型user组成的,接下来我们将使用jQuery实现调用微博接口方法。 首先,我们定义一个全局的对象,它包含三个属性分别是:numWeibo、appendTo和appKey,还有三个方法loadWeibo()、timeAgo()和clean(),具体定义如下:
代码如下: JQWeibo = { // The number of weibos display in the page. // Sets the number of weibos, append class and app key. numWeibo: 15, appendTo: '#jsWeibo', // The appkey you apply from weibo. appKey: YourAppKey, // The function to get weibo data. loadWeibo: function() { }, /** * Convert the time to relative time. * @return {string} relative time like "8 minutes ago" */ timeAgo: function(dateString) { }, ify: { clean: function(weibo) { return this.hash(this.at(this.list(this.link(weibo)))); } } // ify };
上面我们定义了一个对象JQWeibo,其中loadWeibo()方法使用jQuery的Ajax方法向微博API发送跨源请求,接下来让我们实现该方法吧。
代码如下: // The function to get weibo data. loadWeibo: function() { $.ajax({ // Weibo API. url: "http://api..cn/statuses/public_timeline.json", type: "GET", dataType: "jsonp", data: { source: JQWeibo.appKey, count: JQWeibo.numWeibo }, // When the requet completed, then invokes success function. success: function(data, textStatus, xhr) { // Sets html structure. var html = '&div class="weibo"&' + '&a href="/DOMAIN" target="_blank"&USER&/a&' + ':WEIBO_TEXT&div class="time"&AGO&/div&'; // Appends weibos into html page. for (var i = 0; i & data. i++) { $(JQWeibo.appendTo).append( html.replace('WEIBO_TEXT', JQWeibo.ify.clean(data[i].text)) // Uses regex and declare DOMAIN as global, if found replace all. .replace(/DOMAIN/g, data[i].user.domain) .replace(/USER/g, data[i].user.screen_name) .replace('AGO', JQWeibo.timeAgo(data[i].created_at)) ); } } }) }
现在,我们使用$.ajax()方法向微博API发送跨源请求,而且我们向API传递了JQWeibo.appKey和JQWeibo.numWeibo,当请求完成后,调用Success()方法把JSON数据插入的页面当中。 页面的HTML代码如下:
代码如下: &!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"& &html& &head& &meta http-equiv="Content-Type" content="text/charset=UTF-8"& &title&Weibo Feed&/title& &script type="text/javascript" src="/ajax/libs/jquery/1.6.1/jquery.min.js"&&/script& &link rel="stylesheet" type="text/css" href="css/WeiboFeed.css"& &/head& &body& &div id="jsWeibo"&&/div& &/body& &/html& 图8 跨源数据 如上图所示,我们使用$.ajax()方法调用公共微博接口,当成功获取服务器回调数据插入到我们的页面当中。 1.1.3 总结 本文主要介绍了Ajax在同源请求适用性,但在跨源请求中其存在的局限性,进而介绍Ajax和JSONP在跨源请求下解决方法。 回答qianlifeng关于跨源请求的几个问题: 1.一般的跨源不用jsonp请求为什么会报错?和同源的不都是一个请求么?(可能对ajax了解不深) 答:首先跨源请求的解决方法不仅仅有JSON,本文中提及了其他方法,如:表单POST方式、服务器代理、Html5的XDomainRequest和Flash request等;而你提到报错,我觉得你首先要确认数据格式是否正确。关于跨原请求和同源请求本文已经给出了介绍。 2.关于“用Javascript定义回调函数”那块看的不是很明白。传递当前页面的一个js方法给跨源服务器,为什么就能跨源请求了呢?(JSONP?) 服务端根据这个js方法做了什么操作啊? 答:首先我们理解JSON是一种数据格式,而JSONP像似通过一个方法名来封装JSON格式;而跨源请求不是说指定一个回调函数实现的,而是我们利用了浏览器允许跨源请求&script&资源,你也可以我的HTML代码中使用的是Google提供的jQuery库,这也说明了&script&资源可以跨源请求。当我们发送跨源请求后,服务器会返回JSONP,但服务器无法预知接受JSON数据的方法名,所有我们要把函数名告诉(传递)服务器。
代码如下: //JSON {"name":"JK_Rush","id":23} //JSONP func({"name":"JK_Rush","id":23});
3.看你新浪微博的那个例子,是jquery的ajax对跨源做了处理?能不能说说您提到的两种跨源方式的区别或者不同的应用场景,还是随便都一样? 答:是通过$.ajax()方法实现的,如果你想使用动态Javascript实现也可以;至于两种跨源的区别已经在博文中指出了。 回答@On the road....关于JSON反序列化为对象的实现: 答:一般我们可以通过三种方法把JSON数据反序列化为对象,分别是:ASP.NET AJAX中引入的JavaScriptSerializer,WCF中引入的DataContractJsonSerializer,以及Json.NET。 假设,我们获取到员工信息(employee)的JSON数据,它包含两个属性分别是id和复杂属性name,具体如下所示:
代码如下: [ { "id": "82105", "name": { "lastName": "Huang", "firstName": "JK" } }, { "id": "82106", "name": { "lastName": "Leung", "firstName": "Cindy" } } ] string data = "[{\"id\":\"82105\",\"fullname\":{\"lastName\":\"Huang\",\"firstName\":\"JK\"}}," + "{\"id\":\"82106\",\"fullname\":{\"lastName\":\"Leung\",\"firstName\":\"Cindy\"}}]";
根据上述JSON数据的组成,我们定义出相应的对象模型,具体定义如下:
代码如下: // The Employee model. public class Employee { public int Id { } public Name FullName { } } // The Name model. public class Name { public string FirstName { } public string LastName { } }
接下来,我们将介绍使用JavaScriptSerializer,Json.NET和DataContractJsonSerializer反序列化JSON数据为对象。 JavaScriptSerializer
代码如下: var serializer = new JavaScriptSerializer(); var employees= serializer.Deserialize&Employee[]&(data);Json.NET using (var stringReader = new StringReader(data)) using (var jsonTextReader = new JsonTextReader(stringReader)) { var serializer = new JsonSerializer(); var employees = serializer.Deserialize&Employee[]&(jsonTextReader); }
DataContractJsonSerializer 对于使用WCF的DataContractJsonSerializer方法,我们需要在对象模型添加DataContract和DataMember属性,具体定义如下:
代码如下: [DataContract] public class Employee { [DataMember(Name = "id")] public int Id { } [DataMember(Name = "fullname")] public Name FullName { } } [DataContract] public class Name { [DataMember(Name = "firstName")] public string FirstName { } [DataMember(Name = "lastName")] public string LastName { } }
接着我们使用ReadObjects()方法把JSON数据转换为对象。
代码如下: using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List&Employee&)); var employee = (List&Employee&)serializer.ReadObject(ms); }
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 c json append 的文章

 

随机推荐