7、JSON数据和Java对象的相互转换(客户端和服务器对象数据通讯用)

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

    需要使用JSON解析器(它是封装好的工具类),我们测试用用jackson
        * 常见的解析器:Jsonlib,Gson(谷歌),fastjson(阿里巴巴),jackson(MVC内嵌)
    
    一、 JSON转为Java对象步骤
        1. 导入jackson的相关jar包
        2. 创建Jackson核心对象 ObjectMapper
        3. 调用ObjectMapper的相关方法进行转换
            1. readValue(json字符串数据,要转换成的Class类型)
    二、 Java对象转换JSON
        1、使用步骤:
            (1). 导入jackson的相关jar包 --- 注意:拷贝到工程后记得更新
            (2). 创建Jackson核心对象 ObjectMapper
            (3). 调用ObjectMapper的相关方法进行转换
                * 转换方法:(jackson核心对象包含很多方法)
                    * writeValue(参数1,obj):
                        参数1:
                            File:将obj对象转换为JSON字符串,并保存到指定的文件中
                            Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
                            OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
                    * writeValueAsString(obj):将对象转为json字符串

        2. 注解:
            1. @JsonIgnore:排除属性。被排除的键值对就不会被转成字符串,比如在class中的某个成员变量前声明@JsonIgnore,在转换时就不会被转换为JSON字符串
            2. @JsonFormat:属性值得格式化。比如说我们Data数据,默认时是以毫秒格式存在,我们可以在定义该成员变量时加入 @JsonFormat注解来提前设置好格式
                * @JsonFormat(pattern = "yyyy-MM-dd")

        3. 复杂java对象转换
            1. List:数组。转换成的结果格式为:[{},{},{},...]
            2. Map:和对象的格式一致。转成的结果格式为:{"键名":键值,"健名":键值,...}

三、举例:

7、JSON数据和Java对象的相互转换(客户端和服务器对象数据通讯用)_第1张图片

Person.class

package cn.lwgk.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class Person {
    private String name;
    private int age;
    private boolean gender;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    @JsonIgnore
    private String from; //这个将不会执行Json转换

    public Date getBirthday() {
        return birthday;
    }

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

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public boolean isGender() {
        return gender;
    }

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

JsonTest.class

package cn.lwgk.test;

import cn.lwgk.domain.Person;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.util.*;

public class JsonTest {
    @Test
    public void TestJson01() throws Exception {
        //创建java对象
        Person p = new Person();
        p.setName("张珊");
        p.setAge(35);
        p.setGender(true);

        //创建jackson的核心对象 objectMapper
        ObjectMapper obMap = new ObjectMapper();

        //转换
        /*转换方法:
			* writeValue(参数1,obj):
                参数1:
                File:将obj对象转换为JSON字符串,并保存到指定的文件中
                Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
                OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
            * writeValueAsString(obj):将对象转为json字符串*/
        String s = obMap.writeValueAsString(p);

        System.out.println(s);
    }

    /**
     * 测试验证JsonIgnore、JsonFormat
     * @throws Exception
     */
    @Test
    public void TestJson02() throws Exception {
        //创建java对象
        Person p = new Person();
        p.setName("李四");
        p.setAge(32);
        p.setGender(false);
        p.setBirthday(new Date());
        p.setFrom("江西抚州");

        //创建jackson的核心对象 objectMapper
        ObjectMapper obMap = new ObjectMapper();

        String s = obMap.writeValueAsString(p); //{"name":"李四","age":32,"gender":false,"birthday":"2020-05-15"}

        System.out.println(s);
    }

    /**
     * 测试List转换Json
     * @throws Exception
     */
    @Test
    public void TestJson03() throws Exception {
        //创建java对象
        Person p1 = new Person();
        p1.setName("张珊");
        p1.setAge(32);
        p1.setGender(false);
        p1.setBirthday(new Date());
        p1.setFrom("江西南昌");

        Person p2 = new Person();
        p2.setName("李四");
        p2.setAge(31);
        p2.setGender(true);
        p2.setBirthday(new Date());
        p2.setFrom("江西抚州");

        Person p3 = new Person();
        p3.setName("王五");
        p3.setAge(35);
        p3.setGender(true);
        p3.setBirthday(new Date());
        p3.setFrom("江西吉安");

        List pList = new ArrayList();
        pList.add(p1);
        pList.add(p2);
        pList.add(p3);

        //创建jackson的核心对象 objectMapper
        ObjectMapper obMap = new ObjectMapper();

        //[{"name":"张珊","age":32,"gender":false,"birthday":"2020-05-15"},{"name":"李四","age":31,"gender":true,"birthday":"2020-05-15"},{"name":"王五","age":35,"gender":true,"birthday":"2020-05-15"}]
        String s = obMap.writeValueAsString(pList);

        System.out.println(s);
    }

    /**
     * 测试map转换为Json
     * @throws Exception
     */
    @Test
    public void TestJson04() throws Exception {
        //创建map对象
        Map map = new HashMap();
        map.put("name","赵六");
        map.put("age",36);
        map.put("gender","男");


        //创建jackson的核心对象 objectMapper
        ObjectMapper obMap = new ObjectMapper();

        //{"gender":"男","name":"赵六","age":36}
        String s = obMap.writeValueAsString(map);

        System.out.println(s);
    }

    /**
     * json转换为java对象
     * @throws Exception
     */
    @Test
    public void TestJson05() throws Exception {
        //1、初始化JSON字符串
        String json= "{\"name\":\"张珊\",\"age\":32,\"gender\":false,\"birthday\":\"2020-05-15\"}";

        //2、创建ObjectMapper对象
        ObjectMapper obMap = new ObjectMapper();

        //3、转换为JAVA对象--- person对象
        Person p = obMap.readValue(json, Person.class);

        System.out.println(p);//Person{name='张珊', age=32, gender=false, birthday=Fri May 15 08:00:00 CST 2020, from='null'}
    }
}

 

你可能感兴趣的:(13_AJAX&JSON)