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    }}

相關文章
相關標籤/搜索