如果你现在正在使用Restful API,并且你需要通过web项目来构建json格式字符串的响应,那么这篇文章将帮助你使用javascript来创建json格式字符串。这是非常有用的,我们将通过jQuery插件$.toJSON把数据对象转换为json格式。
使用JavaScript构建JSON格式字符串
JavaScript代码
在这里包含了javascript代码。$(“#form”).submit(function(){}- delete_button是form标签的ID,我们通过element.val()调用表单输入框的值。代码如下:
HTML代码
代码如下:
JSON输出
代码如下:
{ "userDetails":{ "user":{ "name":"Srinivas Tamada", "email":"srinivas@9lessons.info", "password":"Srinivas Tamada", "gender":"male", "websites":["www.software8.co","www.heatpress123.net","www.0769zzw.com"] } } }
JSON Encoded
对特殊字符进行编码,会把以下字符进行编码:代码如下:
, / ? : @ & = + $ # jsondata=%7B%22userDetails%22%3A%7B%22user%22%3A%7B%22name%22%3A%22Srinivas%20Tamada%22%2C%22email%22%3A%22srinivas%409lessons.info%22%2C%22password%22%3A%22Srinivas%20Tamada%22%2C%22gender%22%3A%22male%22%2C%22websites%22%3A%5B%22www.9lessons.info%22%2C%22www.egglabs.in%22%2C%22www.fglogin.com%22%5D%7D%7D%7D
GetPostAjax.js
这里定义了jquery的ajax请求方法。代码如下:
function post_data(url,encodedata, success){ $.ajax({ type:"POST", url:url, data :encodedata, dataType:"json", restful:true, contentType: 'application/json', cache:false, timeout:20000, async:true, beforeSend :function(data) { }, success:function(data){ success.call(this, data); }, error:function(data){ alert("Error In Connecting"); } }); }
java创建json对象
// 声明两个json数组 [java] view plain copy print? JSONArray gResTable = new JSONArray(); JSONArray gCmtTable = new JSONArray(); // 声明json对象 ONObject outData = new JSONObject(); //把json数组加到json对象中 [java] view plain copy print?outData.put("ResTable", gResTable); outData.put("CmtTable", gCmtTable); //此时创建出来的如下:jsonData={"ResTable":[],"CmtTable":[]}; 把json数据加到json数组中 for (int i = 0; i < 2; i ++) { JSONObject node = new JSONObject(); node.put("thumb_path", "./Image/" + i +".gif"); node.put("flash_path", "./Image/" + i +".gif"); node.put("desc1", "可疑车辆" + i); node.put("desc2", ""); node.put("desc3", ""); node.put("desc4", ""); node.put("title", "hello"); node.put("upload_time", (new java.util.Date()).toString()); node.put("uploader", "王二"); gResTable.put(node); } for (int i = 0; i < 2; i ++) { JSONObject node = new JSONObject(); node.put("logo_path", "./Image/" + i +".gif"); node.put("comment", "hello"); node.put("comment_time", (new java.util.Date()).toString()); node.put("author", "王二"); gCmtTable.put(node); }
建出来的json格式如下: [java] view plain copy print?/* jsonData={"ResTable":[ {"upload_time":"Sat May 26 20:16:37 CST 2012","title":"hello","flash_path":"./Image/0.gif","uploader":"王二","thumb_path":"./Image/0.gif","desc3":"","desc4":"","desc1":"可疑车辆0","desc2":""}, {"upload_time":"Sat May 26 20:16:37 CST 2012","title":"hello","flash_path":"./Image/1.gif","uploader":"王二","thumb_path":"./Image/1.gif","desc3":"","desc4":"","desc1":"可疑车辆1","desc2":""}], "CmtTable": [{"author":"王二","logo_path":"./Image/0.gif","comment":"hello","comment_time":"Sat May 26 20:16:37 CST 2012"}, {"author":"王二","logo_path":"./Image/1.gif","comment":"hello","comment_time":"Sat May 26 20:16:37 CST 2012"} ]}; */