使用杰克逊反序列化包含@JsonFormat(shape = JsonFormat.Shape.ARRAY)和自定义对象的json [英] Deserializing a json which contains @JsonFormat(shape=JsonFormat.Shape.ARRAY) and custom object using jackson
本文介绍了使用杰克逊反序列化包含@JsonFormat(shape = JsonFormat.Shape.ARRAY)和自定义对象的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义对象:
public class Response
{
@JsonProperty("values")
private List<Value> values;
@JsonFormat(shape=JsonFormat.Shape.ARRAY)
public static class Value {
public Value(long timestamp, float val)
{
this.timestamp = timestamp;
this.val = val;
}
}
}
但是当对此进行解析时,我得到无法从START_ARRAY令牌中反序列化Response $ Value实例". json是:
But when this is being parsed, I get "Can not deserialize instance of Response$Value out of START_ARRAY token". The json is :
{
"values":[[1552215648,18]]
}
知道我是否在这里遗漏了什么吗?还是应该有一个自定义解串器来执行此操作?
Any idea if I'm missing something here? Or should I have a custom deserializer to perform this?
推荐答案
JsonFormat
可以解决问题,但您还需要使用JsonCreator
批注声明构造函数.看下面的例子:
JsonFormat
does the trick but you also need to declare constructor with JsonCreator
annotation. Take a look on below example:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
Response myPojo = mapper.readValue(jsonFile, Response.class);
System.out.println(myPojo);
}
}
class Response {
private List<Value> values;
public List<Value> getValues() {
return values;
}
public void setValues(List<Value> values) {
this.values = values;
}
@Override
public String toString() {
return "Response{" +
"values=" + values +
'}';
}
}
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
class Value {
private long timestamp;
private float val;
@JsonCreator
public Value(@JsonProperty("timestamp") long timestamp, @JsonProperty("val") float val) {
this.timestamp = timestamp;
this.val = val;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public float getVal() {
return val;
}
public void setVal(float val) {
this.val = val;
}
@Override
public String toString() {
return "Value{" +
"timestamp=" + timestamp +
", val=" + val +
'}';
}
}
低于JSON
有效负载的代码上方:
Above code for below JSON
payload:
{
"values": [
[
1552215648,
18
],
[
123,
12.24
]
]
}
打印:
Response{values=[Value{timestamp=1552215648, val=18.0}, Value{timestamp=123, val=12.24}]}
这篇关于使用杰克逊反序列化包含@JsonFormat(shape = JsonFormat.Shape.ARRAY)和自定义对象的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文