2018.7.27 Json与Java相互转换

Posted Legend

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2018.7.27 Json与Java相互转换相关的知识,希望对你有一定的参考价值。

Json.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.2.1.js"></script>
<script type="text/javascript" >
    $(function(){
        $.post("JsonServlet",{method:"entityJson"},function(msg){
            //console.log(msg);//调试
            //接收过来是String   要转成对象才能点里面的属性
            var json = JSON.parse(msg); //字符串---->对象
            $("#Uname").val(json.uname);//给文本框中value赋值
            $("#num").val(json.uid);//给文本框中value赋值
            $("#addr").html(json.address);
        });
        
        
        $.post("JsonServlet",{method:"jsonList"},function(pList){
            //console.log(msg);//调试
            //接收过来是String   要转成对象才能点里面的属性
            var pObj = $.parseJSON(pList);//字符串----->数组对象
            $.each(pObj,function(i,p){
                var li = "<li>"+p.uid+"</li>"+"<li>"+p.uname+"</li>"+"<li>"+p.address+"</li>"+"<br/>";
                $("#myUl").append(li);
            }); 
        });
        
        
        $("#btn").click(function(){
            var url = "JsonServlet";
            var data ={"method":"jsonMap"};
            $.post(url,data,function(pMap){
                var personMap = $.parseJSON(pMap);//json集合字符串转json对象
                $.each(personMap,function(key,value){
                    $.each(value,function(i,person){
                        var li = "<li>"+person.uid+person.uname+person.address+"</li>";
                        $("#myMap").append(li);
                    });
                });
            });
        });
    

        
    })
</script>
</head>
<body>
<h3>Java实体(字符串)转JSON对象  JSON.parse(msg);</h3>
    ID:<input type="text" id="num"><br/>
    Name:<input type="text" id="Uname" ><br/>
    Address:<span id="addr" ></span>
    
<hr>
<h3>Java集合转JSON数组对象  $.parseJSON(pList)</h3>
    <ul id="myUl">
    </ul>
    
    
<hr>

<h3>Map集合转JSON对象</h3>   
<button id=‘btn‘>获取Map集合数据</button>
<ul id="myMap">

</ul>
</body>
</html>

JsonServlet

package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;

import domain.Person;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


@WebServlet("/JsonServlet")
public class JsonServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String method = request.getParameter("method");
        if(method.equals("entityJson")) {
            //设置编码格式  不然会显示乱码
            response.setContentType("text/html;charset=utf-8");
            Person p = new Person(1001, "张三", "男", "广西");
            // 1. java实体转json对象
            JSONObject jsonObj = JSONObject.fromObject(p);
            //发送数据    字符串形式
            response.getWriter().println(jsonObj);
            System.out.println(jsonObj);
            
        }else if(method.equals("jsonList")){
            //设置编码格式  不然会显示乱码
            response.setContentType("text/html;charset=utf-8");
            List<Person> pList = new ArrayList<Person>();
            Person p1 = new Person(1001, "张三", "男", "广西");
            Person p2 = new Person(1002, "李四", "女", "广东");
            Person p3 = new Person(1003, "王五", "男", "四川");
            pList.add(p1);
            pList.add(p2);
            pList.add(p3);
            JSONArray jsonObject =  JSONArray.fromObject(pList);
            System.out.println("集合长度是"+jsonObject.size());
            response.getWriter().println(jsonObject);
        }else if(method.equals("jsonMap")){
            //设置编码格式  不然会显示乱码
            response.setContentType("text/html;charset=utf-8");
            Map<String,Person> mp = new HashMap<String,Person>();
            mp.put("管理员", new Person(1001, "张三", "男", "广西"));
            mp.put("游客", new Person(1002, "张四", "男", "广西"));
            JSONArray jsonMap =  JSONArray.fromObject(mp);
            //发送数据
            response.getWriter().println(jsonMap);
        }
    }

}

以上是关于2018.7.27 Json与Java相互转换的主要内容,如果未能解决你的问题,请参考以下文章

List与Json的相互转换

JSON数据与Java对象的相互转换

JSON 与JAVA数据的相互转换

Java中xml与json的相互转换

Java对象数据与JSON对象数据之间的相互转换(fastjson)

json字符串与java对象的相互转换(jackson)