简体   繁体   English

扩展ArrayList的类未正确序列化

[英]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. 我创建了CustomList类,并在CustomListTest类中进行了测试。 However the problem is that the additional attribute doesn't show up in the json serialization. 但是,问题在于在json序列化中没有显示额外的属性。 So the code below only prints out [1,2,3]. 因此,下面的代码仅打印出[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. 在JSON中,您无法将属性添加到数组。 If you want to get the serialized form {"attribute":false,"list":[]}, you would need a Java object like that: 如果要获取序列化的形式{“ attribute”:false,“ list”:[]},则需要这样的Java对象:

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

As already said by chylis: "prefer composition over inheritance". 正如chylis已经说过的:“比继承更偏爱组成”。 This is a general rule in Java. 这是Java中的一般规则。 Inheritance makes a design often inflexible. 继承使设计通常不灵活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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