java转换json的方式

1.引言

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

 如 Map map=new HashMap();

     map.put("id",1);

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

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

 输出结果是

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


前台页面取值

$.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;
                    }
                 });    
                
  });

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
    }

}





  

转载于:https://my.oschina.net/u/238082/blog/141139

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值