java转换json的方式

1.引言javascript

2.对象json转换一般经常使用Map参数形式,优势是1.属性有key,js前端能够清晰从后台key解析出来 2.MAP参数方便添加其余集合如List即包含可能其余集合的信息,承载的信息能够是多种组合方式.。
html

 如 Map map=new HashMap(); 前端

     map.put("id",1); java

     map.name("name","张三"); jquery

 String result=JSONObject.fromObject(map1).toString();
ajax

 输出结果是 json

  {"id":1,"name":"张三"} async


前台页面取值
post

$.ajax({
                    cache:false,
                    type:'post',
                    async:false,
                    height:350,
                    url:'<%=path%>/jsonServlet',
                    dataType: 'json',
                    timeout: 1000,
                    data:{"txtName":txtName},
                    success: function(data){
                        var obj = eval(data);
                        alert(obj.id); //这里取的是键id
                        $.each(obj,function(i,n){ //循坏开始
                           alert(n);
                           });
                        
                        
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        //alert(XMLHttpRequest.status);
                        return false;
                    }
                 });    
                
  });
ui

js前台取值以下

下面咱们在往Map添加一个List,下面模拟输入模糊查询张

    request.setCharacterEncoding("utf-8");
    response.setContentType("text/json;charset=utf-8");
    response.setCharacterEncoding("utf-8");

    String txtName = request.getParameter("txtName"); // 获取查询姓名

    String personList[] = { "张三", "张一", "张二", "张三", "张四", "张五" }; // 人员信息列表

     List list = new ArrayList();
     Map map = new HashMap();
     int coutnNum = 0;
     if (!txtName.isEmpty()) {
            txtName = txtName.substring(0, 1);
            map.put("id", ++coutnNum);
            for (String person : personList) {
                if (txtName.equals(person.substring(0, 1))) {
                    list.add(person);

                }

            }
            map.put("list", list);

     }

  JSONObject json = JSONObject.fromObject(map);
  String result = json.toString();

 输出结果是{"id":1,"list":["张三","张一","张二","张三","张四","张五"]}

前台页面取值的方式取list的

var obj = eval(data);
 var list=obj.list;
 $.each(list,function(i,n){ //循坏开始
           alert(n);
  });

3.完整列子以下

前台页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta content="text/html; charset=utf-8" http-equiv=Content-Type>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <script type="text/javascript" src="common/js/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){       
             $("#frm1").click(function (){
                var txtName=$("#txtName").val();
                //txtName=encodeURI(encodeURI(txtName));
               // alert(txtName);
                  $.ajax({
                    cache:false,
                    type:'post',
                    async:false,
                    height:350,
                    url:'<%=path%>/jsonServlet',
                    dataType: 'json',
                    timeout: 1000,
                    data:{"txtName":txtName},
                    success: function(data){
                        var obj = eval(data);
                        var list=obj.list;
                        $.each(list,function(i,n){ //循坏开始
                           alert(n);
                           });
                        
                        
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        //alert(XMLHttpRequest.status);
                        return false;
                    }
                 });    
                
                });
       });
    
    </script>

  </head>
 
  <body>
      <input type="text" id="txtName" name="txtName"/>
      <input type="button" id="frm1" value="提交"/>
      <textarea rows="10" cols="50">
        
      </textarea>
  </body>
</html>

4.后台java

package com.test;import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class JsonServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");        doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        response.setContentType("text/json;charset=utf-8");        response.setCharacterEncoding("utf-8");        String txtName = request.getParameter("txtName"); // 获取查询姓名        String personList[] = { "张三", "张一", "张二", "张三", "张四", "张五" }; // 人员信息列表        JSONArray jsonArray = new JSONArray();        List list = new ArrayList();        Map map = new HashMap();        int coutnNum = 0;        if (!txtName.isEmpty()) {            txtName = txtName.substring(0, 1);            map.put("id", ++coutnNum);            for (String person : personList) {                if (txtName.equals(person.substring(0, 1))) {                    list.add(person);                }            }            map.put("list", list);        }        JSONObject json = JSONObject.fromObject(map);        String result = json.toString();        PrintWriter out = response.getWriter();        out.println(result);        out.flush();        out.close();    }    public void init() throws ServletException {        // Put your code here    }}

相关文章
相关标签/搜索