Jackson 对象和JSON的相互转换

Posted

tags:

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

参考技术A 一、Java对象 ⇒ JSON

1.1 转换方式

首先创建转换对象ObjectMappera

ObjectMapper mapper = new ObjectMapper();

该对象主要有两个转换方法

第二种方式:

mapper.writeValue(参数1,p1);

关于参数1

File:将obj对象转换为json字符串,并保存到指定的文件中

Write:将obj对象转换为json字符串,并将json填充到字符输出流中

OutputStream:将obj对象转换为json字符串,并将json填充到字节输出流中

比如:

将JSON字符串数据写入到test.txt文件中:

mapper.writeValue(new File("/Users//Desktop/test.txt"), p1);

1.2 注解使用

@JsonIgnore:排除属性

@JsonIgnore

private Date birthday;

转换最终的JSON字符串中,不会有birthday键值对。

@JsonFormat:属性值格式化

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")

private Date birthday;

转换结果:

“name”:“Alex”,“age”:21,“gender”:“男”,“birthday”:“2019-03-27 06:23:33”

1.3 复杂Java对象转换

List集合转换为JSON字符串:

ObjectMapper mapper = new ObjectMapper();

String json = mapper.writeValueAsString(list);

System.out.println(json);

输出结果:

[“name”:“Alex”,“age”:21,“gender”:“男”,“birthday”:“2019-03-27 06:25:23”,“name”:“Alex”,“age”:21,“gender”:“男”,“birthday”:“2019-03-27 06:25:23”,“name”:“Alex”,“age”:21,“gender”:“男”,“birthday”:“2019-03-27 06:25:23”]

Map集合转换为JSON字符串

public void test4() throws Exception

    Person p1 = new Person();

    p1.setName("Alex");

    p1.setAge(21);

    p1.setGender("男");

    p1.setBirthday(new Date());

    // 创建JavaBean对象

    Map<String, Object> map = new HashMap<String, Object>();

//        map.put("name", "Alex");

//        map.put("age", "1111");

//        map.put("gender", "xxx");

    map.put("k1", p1);

    map.put("k2", p1);

    map.put("k3", p1);

    // 转换

    ObjectMapper mapper = new ObjectMapper();

    String json = mapper.writeValueAsString(map);

    System.out.println(json);



输出结果:

“k1”:“name”:“Alex”,“age”:21,“gender”:“男”,“birthday”:“2019-03-27 06:30:08”,“k2”:“name”:“Alex”,“age”:21,“gender”:“男”,“birthday”:“2019-03-27 06:30:08”,“k3”:“name”:“Alex”,“age”:21,“gender”:“男”,“birthday”:“2019-03-27 06:30:08”

二、JSON ⇒ Java对象

2.1 JSON转换为Java对象

String json = "\"name\":\"Alex\",\"age\":21,\"gender\":\"男\",\"birthday\":\"2019-03-27 06:01:54\"";

ObjectMapper mapper = new ObjectMapper();

Person person = mapper.readValue(json, Person.class);

System.out.println(person);

2.2 JSON转换为Java集合对象

String json = "[\"name\":\"Alex\",\"age\":21,\"gender\":\"男\",\"birthday\":\"2019-03-27 06:01:54\"," +

                "      \"name\":\"Alex\",\"age\":21,\"gender\":\"男\",\"birthday\":\"2019-03-27 06:01:54\"," +

                "      \"name\":\"Alex\",\"age\":21,\"gender\":\"男\",\"birthday\":\"2019-03-27 06:01:54\"]\n";

ObjectMapper mapper = new ObjectMapper();

List<Person> list = mapper.readValue(json, new TypeReference<List<Person>>() );

for (Person p : list)

    System.out.println(p);



输出结果:

Personname=‘Alex’, age=21, gender=‘男’, birthday=Wed Mar 27 14:01:54 CST 2019

Personname=‘Alex’, age=21, gender=‘男’, birthday=Wed Mar 27 14:01:54 CST 2019

Personname=‘Alex’, age=21, gender=‘男’, birthday=Wed Mar 27 14:01:54 CST 2019

Jackson解析Json

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

	* JSON解析器:
		* 常见的解析器:Jsonlib,Gson,fastjson,jackson
	
	1. JSON转为Java对象
		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:排除属性。
					2. @JsonFormat:属性值得格式化
						* @JsonFormat(pattern = "yyyy-MM-dd")

				3. 复杂java对象转换
					1. List:数组
					2. Map:对象格式一致

测试类


import com.code_g.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class TestJackSon {

    //将java对象转换为JavaScript
    @Test
    public void testJack1() throws Exception {
        Person person = new Person();
        person.setName("code_g");
        person.setAge(18);
        person.setGender("male");
        ObjectMapper mapper = new ObjectMapper();
//        String s = mapper.writeValueAsString(person);   //将对象转换为json字符串
//        System.out.println(s);  //{"name":"code_g","age":18,"gender":"male"}

        //将对象转为json在写入文件中
        mapper.writeValue(new File("E:\\\\a.txt"),person);
    }

    //测试注解
    @Test
    public void testJack2() throws Exception {
        Person person = new Person();
        person.setName("code_g");
        person.setAge(18);
        person.setGender("male");
        person.setBirthday(new Date());
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(person);
        System.out.println(s);
        //{"name":"code_g","age":18,"gender":"male","birthday":1620825617349}
        //加@JsonIgnore注解 {"name":"code_g","age":18,"gender":"male"}
        //加@JsonFormat注解 {"name":"code_g","age":18,"gender":"male","birthday":"2021-05-12"}
    }

    //数组转换
    @Test
    public void testJack3() throws Exception {
        Person person1 = new Person();
        person1.setName("code_g");
        person1.setAge(18);
        person1.setGender("male");
        person1.setBirthday(new Date());

        Person person2 = new Person();
        person2.setName("code_g");
        person2.setAge(18);
        person2.setGender("male");
        person2.setBirthday(new Date());

        Person person3 = new Person();
        person3.setName("code_g");
        person3.setAge(18);
        person3.setGender("male");
        person3.setBirthday(new Date());

        ArrayList<Person> list = new ArrayList<>();
        list.add(person1);
        list.add(person2);
        list.add(person3);

        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(list);
        System.out.println(s);
        //[
        // {"name":"code_g","age":18,"gender":"male","birthday":"2021-05-12"},
        // {"name":"code_g","age":18,"gender":"male","birthday":"2021-05-12"},{
        // "name":"code_g","age":18,"gender":"male","birthday":"2021-05-12"}
        // ]
    }

    //map
    @Test
    public void testJack4() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","code_g");
        map.put("age",18);
        map.put("gender","female");
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(map);
        System.out.println(s);
        //{"gender":"female","name":"code_g","age":18}
    }

    //将json转换为java对象
    @Test
    public void testJack5() throws Exception {
        String s = "{\\"gender\\":\\"female\\",\\"name\\":\\"code_g\\",\\"age\\":18}";
        ObjectMapper mapper = new ObjectMapper();
        Person person = mapper.readValue(s, Person.class);
        System.out.println(person);     //Person{name=\'code_g\', age=18, gender=\'female\', birthday=null}
    }
}


Person类


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 String gender;

//    @JsonIgnore
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

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

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

    public Person(String name, int age, String gender, Date birthday) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.birthday = birthday;
    }

    public Person() {
    }

    public Person(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    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 String getGender() {
        return gender;
    }

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

}



以上是关于Jackson 对象和JSON的相互转换的主要内容,如果未能解决你的问题,请参考以下文章

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

Jackson 框架JSONXMLListMap直接相互转换

json与对象相互转换

XML编程总结——使用JAXB进行java对象和xml格式之间的相互转换

Java:JSON和Map相互转换

Scala中json格式字符串map相互转换