[英]Can't serialize with Jackson Json class fields if it extends ArrayList
I'm using Jackson Json.我正在使用杰克逊 Json。 I can't serialize class fields if class extends ArrayList.
如果类扩展了 ArrayList,我将无法序列化类字段。
Class:班级:
public class DataElement {
private Date date;
private int val1;
private int val2;
// constructor, getters, setters
}
public class DataArray extends ArrayList<DataElement> {
private String info;
private int num;
// constructor, getters, setters
}
Serialization:序列化:
ObjectMapper jsonMapper = new ObjectMapper();
jsonMapper.writeValue(new File("path"), dataArray);
Result file contains DataElements only:结果文件仅包含数据元素:
[ {
"date" : 1446405540000,
"val1" : 10296,
"val2" : 30365
}, {
"date" : 1446405600000,
"val1" : 40164,
"val2" : 20222
} ]
'num' and 'info' are not saved into file. 'num' 和 'info' 不会保存到文件中。
How to save full class including its fields?如何保存完整的类,包括其字段?
Jackson will serialize your POJOs according to the JsonFormat.Shape
. Jackson 将根据
JsonFormat.Shape
序列化您的 POJO。 For an ArrayList
object that is ARRAY
.对于为
ARRAY
的ArrayList
对象。 You can change the shape to OBJECT
with an annotation.您可以使用注释将形状更改为
OBJECT
。
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public class DataArray extends ArrayList<DataElement> {
Make sure DataArray
has a getter that returns an ArrayList
for eg确保
DataArray
有一个 getter 返回一个ArrayList
例如
public ArrayList<DataElement> getContents() {
return new ArrayList<>(this);
}
When I tried the above code I saw this field at the resulting JSON当我尝试上面的代码时,我在结果 JSON 中看到了这个字段
"empty":false
You can use @JsonIgnore
to prevent that from appearing您可以使用
@JsonIgnore
来防止它出现
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.