0%

JackJson和FastJson常见操作

Jackjson

配置:

1
2
3
4
5
6
7
8
9
10
11
12
ObjectMapper objectMapper = new ObjectMapper();
//Include.ALWAYS 是序列化对像所有属性
//Include.NON_NULL 只有不为null的字段才被序列化
//Include.NON_EMPTY 如果为null或者 空字符串和空集合都不会被序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//如果是空对象的时候,设置为false不抛异常,也就是对应的属性没有get方法,默认是true,即会抛异常
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//反序列化的时候如果多了其他属性,不抛出异常
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

yml配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
spring:
jackson:
# 设置属性命名策略,对应jackson下PropertyNamingStrategy中的常量值,SNAKE_CASE-返回的json驼峰式转下划线,json body下划线传到后端自动转驼峰式
property-naming-strategy: SNAKE_CASE
# 全局设置@JsonFormat的格式pattern
date-format: yyyy-MM-dd HH:mm:ss
# 当地时区
locale: zh
# 设置全局时区
time-zone: GMT+8
# 常用,全局设置pojo或被@JsonInclude注解的属性的序列化方式
default-property-inclusion: NON_NULL #不为空的属性才会序列化,具体属性可看JsonInclude.Include
# 常规默认,枚举类SerializationFeature中的枚举属性为key,值为boolean设置jackson序列化特性,具体key请看SerializationFeature源码
serialization:
WRITE_DATES_AS_TIMESTAMPS: true # 返回的java.util.date转换成timestamp
FAIL_ON_EMPTY_BEANS: true # 对象为空时是否报错,默认true
# 枚举类DeserializationFeature中的枚举属性为key,值为boolean设置jackson反序列化特性,具体key请看DeserializationFeature源码
deserialization:
# 常用,json中含pojo不存在属性时是否失败报错,默认true
FAIL_ON_UNKNOWN_PROPERTIES: false
# 枚举类MapperFeature中的枚举属性为key,值为boolean设置jackson ObjectMapper特性
# ObjectMapper在jackson中负责json的读写、json与pojo的互转、json tree的互转,具体特性请看MapperFeature,常规默认即可
mapper:
# 使用getter取代setter探测属性,如类中含getName()但不包含name属性与setName(),传输的vo json格式模板中依旧含name属性
USE_GETTERS_AS_SETTERS: true #默认false
# 枚举类JsonParser.Feature枚举类中的枚举属性为key,值为boolean设置jackson JsonParser特性
# JsonParser在jackson中负责json内容的读取,具体特性请看JsonParser.Feature,一般无需设置默认即可
parser:
ALLOW_SINGLE_QUOTES: true # 是否允许出现单引号,默认false
# 枚举类JsonGenerator.Feature枚举类中的枚举属性为key,值为boolean设置jackson JsonGenerator特性,一般无需设置默认即可
# JsonGenerator在jackson中负责编写json内容,具体特性请看JsonGenerator.Feature

各种转换:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//map转对象
System.out.println("==== map->对象 =====");
User user = objectMapper.convertValue(map, User.class);

//将对象写成json串
System.out.println("==== 对象->json串 =====");
String jsonStr = objectMapper.writeValueAsString(map);
System.out.println(jsonStr);

//json串转换成json节点对象
System.out.println("==== json串-->json节点对象 =====");
JsonNode jsonNode = objectMapper.readTree(jsonStr);
System.out.println(jsonNode);
System.out.println(jsonNode.get("name").asText());
System.out.println(jsonNode.get("age").asInt());

// json串转换成实体对象(map)
System.out.println("==== json串-->实体对象(map) =====");
Map param = objectMapper.readValue(jsonStr, Map.class);
Person person = objectMapper.readValue(jsonStr, Person.class);
System.out.println(param);
System.out.println(person);

// json串转换成集合对象
System.out.println("==== json串 --> 集合对象 =====");
List<Person> list = new ArrayList<>();
list.add(new Person("李四",24));
String listStr = objectMapper.writeValueAsString(list);
//no.1
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Person.class);
List<Person> persons = (List<Person>)objectMapper.readValue(listStr, javaType);
System.out.println(persons);
//no.2
List<Person> persons2 = objectMapper.readValue(listStr, new TypeReference<List<Person>>() {})

//xml转成对象
//对象需加上注解映射@JacksonXmlRootElement、@JacksonXmlProperty、@JacksonXmlElementWrapper、@JacksonXmlCData、@JacksonXmlText
System.out.println("==== xml串 --> 对象 =====");
XmlMapper xmlMapper = new XmlMapper();
User user = xmlMapper.readValue(xml, User.class);
//对象转成xml
System.out.println("==== 对象 --> xml =====");
XmlMapper xmlMapper = new XmlMapper();
String xmlStr = xmlMapper.writeValueAsString(user)

Fastjson

各种转换:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//将对象转换成json串
System.out.println("==== 对象->json串 =====");
Person p = new Person("李四", 24);
String jsonString = JSON.toJSONString(p);
System.out.println(jsonString);

// json串转换成实体对象(map)
System.out.println("==== json串-->实体对象(map) =====");
Person person = JSON.parseObject(jsonString, Person.class);
Map map = JSON.parseObject(jsonString, Map.class);
JSONObject jsonObject = JSON.parseObject(jsonString);
System.out.println(person);
System.out.println(map);
System.out.println(jsonObject);

// json串转换成集合对象
System.out.println("==== json串 --> 集合对象 =====");
List<Person> list = new ArrayList<>();
list.add(p);
String listStr = JSON.toJSONString(list);
List<Person> peoples = JSON.parseArray(listStr, Person.class);
JSONArray jsonArray = JSON.parseArray(listStr);
System.out.println(peoples);
System.out.println(jsonArray);


@Configuration
public class HttpConverterConfig {

@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
// 1.定义一个converters转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 2.添加fastjson的配置信息,比如: 是否需要格式化返回的json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 3.在converter中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
// 4.将converter赋值给HttpMessageConverter
HttpMessageConverter<?> converter = fastConverter;
// 5.返回HttpMessageConverters对象
return new HttpMessageConverters(converter);
}
}

Jackson2HashMapper

org.springframework.data.redis.hash

1
2
3
4
5
Jackson2HashMapper jackson2HashMapper = new Jackson2HashMapper(objectMapper,false);
//对象转map
Map<String, Object> map = jackson2HashMapper.toHash(user);
//map转对象
Object o = jackson2HashMapper.fromHash(map);