简体   繁体   中英

Class that extends ArrayList doesn't serialize properly

I want to make a custom list that behaves similar to array list except that it has one additional attribute. I created the CustomList class and did the test in the CustomListTest class. However the problem is that the additional attribute doesn't show up in the json serialization. So the code below only prints out [1,2,3]. Is there a way to do this such that the attribute is also included in the serialization?

import java.util.ArrayList;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class CustomList<T> extends ArrayList<T> {
    private boolean attribute = false;
}

public class CustomListTest {
    public static void main(String[] args) throws JsonProcessingException {
        CustomList<Integer> a = new CustomList<Integer>();

        a.add(1);
        a.add(2);
        a.add(3);

        ObjectMapper mapper = new ObjectMapper();

        System.out.println(mapper.writeValueAsString(a));
    }
}

The problem is that there is no field with name list. In JSON you cannot add attributes to an array. If you want to get the serialized form {"attribute":false,"list":[]}, you would need a Java object like that:

private static class ComposeList<T> {
  boolean attribute = false;
  ArrayList<T> list = new ArrayList<>();
}

As already said by chylis: "prefer composition over inheritance". This is a general rule in Java. Inheritance makes a design often inflexible.

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