Jackson 对象和JSON的相互转换

如题所述

第1个回答  2022-06-26
一、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);

}

输出结果:

Person{name=‘Alex’, age=21, gender=‘男’, birthday=Wed Mar 27 14:01:54 CST 2019}

Person{name=‘Alex’, age=21, gender=‘男’, birthday=Wed Mar 27 14:01:54 CST 2019}

Person{name=‘Alex’, age=21, gender=‘男’, birthday=Wed Mar 27 14:01:54 CST 2019}
相似回答