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

十年热恋 提交于 2019-11-28 08:48:40

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

  • JSON解析器

    常见的解析器:Jsonlib 、Gson、 fastjson、 jackson

  1. JSON转化为Java对象

    1. 使用步骤:

      1、导入jackson的相关jar包
      2、创建jackson核心对象ObjectMapper
      3、使用ObjectMapper的相关方法进行转换
          1、readValue(json字符串数组,Class)
  2. Java转化为JSON对象

    1. 使用步骤

      1、导入jackson的相关jar包
      2、创建jackson核心对象ObjectMapper
      3、使用ObjectMapper的相关方法进行转换
      1. 转换方式:

         * writeValue(参数1,obj):
        参数1:
        File:将obj对象转换为JSON字符串,并保存到指定的文件中
        Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
        OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
         * writeValueAsString(obj):将对象转为json字符串
      2. 注解

        1. @JsonIgnore:排除属性。
      3. @JsonFormat:属性值得格式化

        • @JsonFormat(pattern = "yyyy-MM-dd")
        1. 复杂Java对象转换
          1. List:数组
          2. Map:对象格式一致

创建person类

public class Person {
 private String name;
 private Integer age;
 private String gender;
 //@JsonIgnore //忽略该属性
 @JsonFormat(pattern = "yyyy-MM-dd")//属性格式化
 private Date birthday;

 public Date getBirthday() {
     return birthday;
 }

 public void setBirthday(Date birthday) {
     this.birthday = birthday;
 }
 public Person() {
 }

 @Override
 public String toString() {
     return "Person{" +
             "name='" + name + '\'' +
             ", age=" + age +
             ", gender='" + gender + '\'' +
             '}';
 }

 public String getName() {
     return name;
 }

 public void setName(String name) {
     this.name = name;
 }

 public Integer getAge() {
     return age;
 }

 public void setAge(Integer age) {
     this.age = age;
 }

 public String getGender() {
     return gender;
 }

 public void setGender(String gender) {
     this.gender = gender;
 }
}

Java转化为JSON对象

JacksonTest

public class JacksonTest {

 //Java对象转为JSON
 @Test
 public void test1() throws IOException {
     //创建Person对象
     Person person = new Person();
     person.setName("张三");
     person.setAge(21);
     person.setGender("男");
     ObjectMapper om = new ObjectMapper();
     /*
     writeValue(参数,obj)
     参数1.:
            File:将对象转换为json字符串,并保存指定的文件中
            Writer:将对象转换为json字符串,并将json数据填充到字符输出流中
            Outputstream:将对象转换为json字符串,并将json数据填充到字节输出流中
      */
     /*//writeValue写到D://a.txt中
     om.writeValue(new File("D://a.txt"),person);*/
     //writeValue,数据关联到Writer中
     // om.writeValue(new FileWriter("d://b.txt"),person);

     //将对象转化成json对象
     String s = om.writeValueAsString(person);
     System.out.println(s);
 }

 @Test
 public void test2() throws IOException {
     //创建Person对象
     Person person = new Person();
     person.setName("张三");
     person.setAge(21);
     person.setGender("男");
     person.setBirthday(new Date());
     ObjectMapper om = new ObjectMapper();
     String s = om.writeValueAsString(person);
     System.out.println(s);

 }

 @Test
 public void test3() throws IOException {
     //创建Person对象
     Person person = new Person();
     person.setName("张三");
     person.setAge(21);
     person.setGender("男");
     person.setBirthday(new Date());
     //创建Person对象
     Person person1 = new Person();
     person1.setName("张三");
     person1.setAge(21);
     person1.setGender("男");
     person1.setBirthday(new Date());
     //创建Person对象
     Person person2 = new Person();
     person2.setName("张三");
     person2.setAge(21);
     person2.setGender("男");
     person2.setBirthday(new Date());

     //创建list集合
     List<Person> list = new ArrayList<Person>();
     list.add(person);
     list.add(person1);
     list.add(person2);
     ObjectMapper om = new ObjectMapper();
     String s = om.writeValueAsString(list);
     System.out.println(s);
     /**
         * 输出结果:
         * [{"name":"张三","age":21,"gender":"男","birthday":"2019-08-23"},
         * {"name":"张三","age":21,"gender":"男","birthday":"2019-08-23"},
         * {"name":"张三","age":21,"gender":"男","birthday":"2019-08-23"}]
      *
      */

 }

 @Test
 public void test4() throws IOException {
     Map<String,Object> map=new HashMap<String, Object>();
     map.put("name","李四0");
     map.put("age",23);
     map.put("gender","男");

     ObjectMapper om = new ObjectMapper();
     String s = om.writeValueAsString(map);
     System.out.println(s);
     /**
         * 输出结果:
         * {"gender":"男","name":"李四0","age":23}
      */
 }
}

JSON转化为Java对象

   public class JacksonTest {
   @Test
    public void test5() throws IOException {
        //初始化
        String json="{\"gender\":\"男\",\"name\":\"李四0\",\"age\":23}";
        ObjectMapper ob=new ObjectMapper();
        //转化为Java对象 person对象
        Person person = ob.readValue(json, Person.class);
        System.out.println(person);
    }
    }

案例--效验用户名是否存在

当文本输入框失去焦点,发送ajax请求,查询数据库中是否存在该用户

​ 存在:提示存在

​ 不存在:提示可用

1. 服务器响应的数据,在客户端使用时,要想当做json数据格式使用。有两种解决方案:
    1. $.get(type):将最后一个参数type指定为"json"
    2. 在服务器端设置MIME类型
        response.setContentType("application/json;charset=utf-8");

效果图:

Servlet

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletContext;
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 java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //期望服务器响应回应的格式 {"userExsit":"true","msg":"用户名此用户名太受欢迎,请更换一个"}
        //                          "userExsit":"false","msg":"用户名可用"}
        Map<String, Object> map = new HashMap<String, Object>();
        //设置相应格式为json
        response.setContentType("application/json;charset=utf-8");
        //获取用户名
        String username = request.getParameter("username");
        System.out.println(username);
        //查询数据库
        if ("tom".equals(username)) {
            map.put("userExsit", true);
            map.put("msg", "用户名此用户名太受欢迎,请更换一个");

        } else {
            map.put("userExsit", false);
            map.put("msg", "用户名可用");
        }
        System.out.println(map);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(response.getWriter(), map);


    }

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

html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            input {
                padding: 10px;
                margin: 5px;
            }

        </style>
        <script src="js/jquery-3.3.1.min.js"></script>
        <script>
            $(function () {
                $("#username").blur(function () {
                    //获取username的值
                    var username = $(this).val();

                    //发送ajax请求
                    //期望服务器响应回应的格式 {"userExsit":"true","msg":"用户名此用户名太受欢迎,请更换一个"}
                    //                          "userExsit":"false","msg":"用户名可用"}
                    $.get("findUserServlet",{"username":username},function (data) {

                        var span = $("#sp");
                        // 判断userExsit的值是否是true

                        if (data.userExsit) {
                            //存在
                            span.html(data.msg)

                            span.css("color", "red");
                        } else {
                            // 不存在
                            span.html(data.msg)
                            span.css("color", "green");

                        }
                        //1.
                        //},"json");
                    });
                });
            })

        </script>
    </head>
    <body>
        <div align="center">
            <form action="" method="post">
                用户名:<input type="text" id="username" name="username" placeholder="请输入用户名"><br><span id="sp" class="span"></span><br>
                密&ensp;&ensp;码:<input type="password" name="password" placeholder="请输入密码"><br>
                <input type="submit" value="注册">
            </form>
        </div>
    </body>
</html>

源码地址GitHub:https://github.com/PoetryAndYou/JQuery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!