【发布时间】:2017-06-27 16:51:54
【问题描述】:
是否有 Jackson 注释允许将数组反序列化为我的 POJO 的特定字段?我可以使用自定义反序列化器轻松地做到这一点,但我希望能在课堂上完成这项工作。
例如,我从 Elasticsearch 返回以下 JSON。
{
"_index": "twitter",
"_type": "tweet",
"_id": "AVodOsgk0etILSbJamY-",
"_score": null,
"_source": {
"tweetText": "I'm at Residencial Nova Alegria https:\/\/t.co\/4TyK8PAWzB",
"placeCountry": "Brasil",
"screenName": "wildelson",
"cleanedText": "I'm at Residencial Nova Alegria https:\/\/t.co\/4TyK8PAWzB",
"resolvedUrls": [
"https:\/\/www.swarmapp.com\/c\/gfULJdQ6umw"
],
"tweetId": "829272906291085314",
"tweetDate": 1486549042000
},
"sort": [
1486549042000,
"tweet#AVodOsgk0etILSbJamY-"
]
}
我的POJO如下:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Data;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder(value = {
"enrichedStatus",
"sortValue",
"uid"
})
public class TweetHit {
private final EnrichedStatus enrichedStatus;
private final Long sortValue;
private final String uid;
public TweetHit(EnrichedStatus enrichedStatus, Long sortValue, String uid) {
this.enrichedStatus = enrichedStatus;
this.sortValue = sortValue;
this.uid = uid;
}
我希望对“排序”数组进行反序列化,该数组在数组[0] 中总是有一个长字符,在数组[1] 中是一个字符串:
Long sortValue = sort[0]
String uid = sort[1]
我发现了另一个问题,唯一的答案是自定义反序列化器,如果可以的话,我想避免。 Jackson: Deserialize JSON-Array in different attributes of an object
我想也许我可以以某种方式将@JsonProperty("sort") 与@JsonFormat(shape = ARRAY) 一起使用,但无论如何我都看不到要指定要反序列化到每个字段中的特定单元格。
注意,这是一个不可变对象,因此我可能需要解决方案与构造函数一起工作,尽管我可以删除 final,添加一个空构造函数,将注释放在字段级别并使用 Lombok 禁用杰克逊是否可以直接设置到字段中?
【问题讨论】: