JavaScript 构建 JSON 字符串教程:Restful API 前端传参 + Java 后端构建 JSON

🕒 2026-01-06 14:28:18
📁 JSON学习教程
作者:JSONLA小编

一、技术背景补充

在 Restful API 交互场景中,JSON(JavaScript Object Notation)是前后端数据传输的核心格式。前端需将表单、用户输入等结构化数据转换为 JSON 字符串,后端(如 Java)则需解析或构建 JSON 数据响应。相比手动拼接 JSON 字符串(易出错、难维护),通过 JavaScript 对象转换为 JSON 字符串是更规范的方式,而 jQuery 的$.toJSON插件(基于 JSON.stringify 规范)能高效完成这一转换,同时规避语法错误(如引号嵌套、逗号遗漏)。需要明确的核心概念:

  • JSON 对象 vs JSON 字符串:JSON 对象是 JavaScript 中的原生对象({name: "test"}),JSON 字符串是符合 JSON 语法的字符串('{"name":"test"}'),接口传输必须使用字符串格式。
  • encodeURIComponent 作用:对 JSON 字符串编码可避免特殊字符(如&、=、@)导致的 URL 参数截断或解析错误,是前端传参的必备步骤。
  • Restful API 适配:设置contentType: 'application/json'可明确告知后端请求体为 JSON 格式,符合 Restful 规范的参数传递要求。

二、使用 JavaScript 构建 JSON 格式字符串

JavaScript 代码

<script src="jquery.min.js"></script> 

<script src="jquery.json-2.2.js"></script> 

<script src="GetPostAjax.js"></script> 

<script type="text/javascript"> 

$(document).ready(function() 

$("#form").submit(function(e){ 

e.preventDefault(); 

var username,email,password,gender; 

username=$("#username").val(); 

email=$("#email").val(); 

password=$("#username").val(); 

gender=$("#gender").val(); 

if(username.length>0 && email.length>0 && password.length>0 &&gender.length>0) 

//Creating Objects 

var request = new Object(); 

var userDetails = new Object(); 

var user = new Object(); 

var websites=new Array(); 

user.name=username; 

user.email=email; 

user.password=password; 

user.gender=gender; 

//Array Push 

if(website1.length>0) 

websites.push(website1); 

if(website2.length>0) 

websites.push(website2); 

if(website3.length>0) 

websites.push(website3); 

user.websites=websites; 

userDetails.user = user; 

request.userDetails = userDetails; 

var jsonfy = $.toJSON(request); 

// Encodes special characters 

var encodedata = 'jsondata='+encodeURIComponent(jsonfy); 

//Ajax Call 

var url='website API URL'; 

post_data(url,encodedata, function(data) { 

alert("Success"); 

}); 

}); 

}); 

</script"> 

关键说明

  1. e.preventDefault():核心作用是取消表单的默认提交行为,保证 AJAX 异步提交生效,是前端表单异步处理的基础。
  2. 层级对象构建:request -> userDetails -> user的层级结构对应最终 JSON 的嵌套格式,符合 Restful API 对数据结构的规范要求。
  3. 插件替代方案:若不使用jquery.json-2.2.js,现代浏览器可直接使用原生JSON.stringify(request),效果完全一致且无需额外插件。

HTML 代码

<form method='post' action='' id='form'> 

Name 

<input type='text' name='username' id='username' /> 

Email 

<input type='text' name='email' id='email' /> 

Password 

<input type='text' name='password' id='password' /> 

Gender 

<select name='gender' id='gender'><option value='male'>Male</option><option value='female'>Female</option></select> 

Websites 

<input type='text' id='website1' /> 

<input type='text' id='website2' /> 

<input type='text' id='website3' /> 

<input type='submit' id='submit'/> 

</form> 

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 格式要求:键名必须用双引号包裹,字符串值也必须用双引号(单引号会导致后端解析失败),$.toJSON会自动处理这一规范,避免手动拼接的语法错误。
  • 数组处理:websites数组在 JSON 中保持原生数组格式,后端可直接按数组类型解析。

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

编码原理

  • encodeURIComponent会将特殊字符转换为 UTF-8 编码的百分号形式(如"→%22、@→%40),确保参数在 HTTP 传输中不被篡改,后端需用decodeURIComponent反向解码。

GetPostAjax.js

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

}); 

}

AJAX 配置说明

  1. contentType: 'application/json':指定请求体的 MIME 类型为 JSON,后端框架(如 SpringMVC)可直接绑定到 Java 对象。
  2. dataType:"json":告知 jQuery 期望后端返回 JSON 格式数据,会自动解析为 JavaScript 对象。
  3. 错误处理优化:建议将alert("Error In Connecting")替换为console.log(data),并展示具体错误码 / 信息,便于调试。

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

}

技术说明

  1. 依赖说明:上述代码使用的是org.json包(JSON-Java 库),需在 Maven 中引入依赖:
  2. <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20231013</version> </dependency>

最终 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"} 

 ]}; 

*/ 



相关推荐

正在加载... ...