# jackson JSON 框架

# 序列化和反序列化使用不同的属性名称

场景:比如你调用一个第三方接口,返回给你的字段名称是 hit_sentence,你写了一个类来接受该字段,但是希望在将该对象序列化为 JSON 字符串时,还是使用类的属性名称,即 hitSentence 可以如下事项

import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;

public class HotTopicPostRes {
    @Schema(description = "内容")
    @JsonAlias("hit_sentence")
    @JsonProperty("hitSentence")
    private String hitSentence;
}
1
2
3
4
5
6
7
8
9

测试如下

package cn.mrcode.dto;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

class HotTopicPostResTest {

    @Test
    public void demo() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = """
                {
                        "id": "7e77ad533958c95b61c64f4ca39cbfa0c76a300fe0996ea6070e3adfb1cc4e02",
                        "channel": "Twitter",
                        "country": "Germany",
                        "headline": null,
                        "engagement": null,
                        "reach": 611,
                        "sentiment": "Neutral",
                        "views": null,
                        "hit_sentence": "RT @TerrillCharming: -Space X -Tesla Model X -Twitter has a bunch of porn so that makes it XXX. ; Why did he choose X to be the name of Twitter? What was the reasoning?",
                        "authorName": "@ODB_36"
                      }
                """;
        HotTopicPostRes res = objectMapper.readValue(jsonStr, HotTopicPostRes.class);
        System.out.println(objectMapper.writeValueAsString(res));
    }

}
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

输出的 json 字符串如下

{
    "id": "7e77ad533958c95b61c64f4ca39cbfa0c76a300fe0996ea6070e3adfb1cc4e02",
    "channel": "Twitter",
    "country": "Germany",
    "headline": null,
    "date": null,
    "url": null,
    "engagement": null,
    "reach": 611,
    "sentiment": "Neutral",
    "views": null,
    "hitSentence": "RT @TerrillCharming: -Space X -Tesla Model X -Twitter has a bunch of porn so that makes it XXX. ; Why did he choose X to be the name of Twitter? What was the reasoning?",
    "authorName": "@ODB_36"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# Controller 如何支持 JDK8 时间格式

当你使用 LocalDateTime 当参数接收时,传递 2021-01-01 22:00:00 会报错,提示无法解析

Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2021-01-01 22:00:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2021-01-01 22:00:00' could not be parsed at index 10
 at [Source: (PushbackInputStream); line: 2, column: 16] (through reference chain: com.meshop.crm.controller.checkoutorder.meshop.dto.CheckoutOrderSearchReq["beginDate"])
	at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67)
	at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1702)
	at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:947)
	at com.fasterxml.jackson.datatype.jsr310.deser.JSR310DeserializerBase._handleDateTimeException(JSR310DeserializerBase.java:129)
	at com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer.deserialize(LocalDateTimeDeserializer.java:102)
	at com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer.deserialize(LocalDateTimeDeserializer.java:39)
	at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:371)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:164)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3521)
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:376)
	... 105 common frames omitted
Caused by: java.time.format.DateTimeParseException: Text '2021-01-01 22:00:00' could not be parsed at index 10
	at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
	at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
	at java.time.LocalDateTime.parse(LocalDateTime.java:492)
	at com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer.deserialize(LocalDateTimeDeserializer.java:100)
	... 112 common frames omitted
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

根据日志来看,有一个 LocalDateTimeDeserializer,说明是有这个配置的,但是他无法解析 2021-01-01 22:00:00 这种格式,那么就需要如下方式更改 Jackson 相关配置 (opens new window)