java 后台接受JSON字段及发送JSON数组
发送JSON字段
public class SubmitServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data =request.getParameter("data");
//接受收据(此时是字符串,但是是字符串格式的)
System.out.println("服务端接收到的数据是:" +data);
//将字符串格式的字段转换为JSon字段
JSONObject json=JSONObject.fromObject(data);
System.out.println("转换为JSON对象之后是:"+ json);
//将JSon字段转换为Java类
Hero hero = (Hero)JSONObject.toBean(json,Hero.class);
System.out.println("转换为Hero对象之后是:"+hero);
response.setContentType("text/plain");
response.getWriter().print(JSONSerializer.toJSON(heros).toString());
}
}
如果发送JSON数组
List<AcceptedDetail> rets = getAcceptedDetail.getAcceptedList(mouth);
System.out.println("aaaaaaaaa"+mouth+ "ret cnt : "+ rets.size() );
//转化为JSON字段
String jsonRets =JSONSerializer.toJSON(rets).toString();
response.setContentType("text/html;charset=utf-8");
//response.getWriter().print(jsonRets);;
PrintWriter out = response.getWriter();
out.print(jsonRets);
如果返回JSON字段
JSONObject retJson= new JSONObject();
retJson.put("name", retHero.getName());
retJson.put("hp", retHero.getHp()+"");
response.setContentType("text/html;charset=utf-8");
response.getWriter().print(retJson);
JS发送JSON字段以及解析JSON数组:
<script>
$('#sender').click(function(){
var name=document.getElementById('name').value;
var hp=document.getElementById('hp').value;
var hero={"name":name,"hp":hp};
var url="submitServlet";
$.post(
url,
{"data":JSON.stringify(hero)},
function(data) {
var json=JSON.parse(data);
var name =json[2].name;
var hp = json[3].hp;
alert("提交成功,获得"+name+"血量"+hp);
});
});
</script>