简体   繁体   中英

Can't serialize with Jackson Json class fields if it extends ArrayList

I'm using Jackson Json. I can't serialize class fields if class extends 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.

How to save full class including its fields?

Jackson will serialize your POJOs according to the JsonFormat.Shape . For an ArrayList object that is ARRAY . You can change the shape to OBJECT with an annotation.

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public class DataArray extends ArrayList<DataElement> {

Make sure DataArray has a getter that returns an ArrayList for eg

public ArrayList<DataElement> getContents() {
    return new ArrayList<>(this);
}

When I tried the above code I saw this field at the resulting JSON

"empty":false

You can use @JsonIgnore to prevent that from appearing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM