0

I'm writing a subclass extends ArrayList, and then use JSON to 'encode' it. However, the new class fields are missing in the output

    @Data
    public static class NewArray<T> extends ArrayList<T> {
        private String testField;

        public NewArray(Collection<T> c, String msg) {
            super(c);
            testField = msg;
        }
    }
        Gson gson = new GsonBuilder().create();
        List<Integer> input = Lists.newArrayList(111, 222);
        NewArray n = new NewArray(input, "test field");
        System.out.println(gson.toJson(n))

The output is:

[111,222]

No testField output

What am I missing here?

Should I use combination instead?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
xgwang
  • 614
  • 7
  • 21
  • Does this answer your question? [Gson doesn't serialize fields defined in subclasses](https://stackoverflow.com/questions/8153582/gson-doesnt-serialize-fields-defined-in-subclasses) – akortex Jul 30 '21 at 06:40
  • Haven't used Gson in a while, but based on the exact code, you have neither a `getTestField()` or an annotation `@JsonProperty` (in Jackson, I'm sure Gson has the same). – kendavidson Jul 30 '21 at 17:15

0 Answers0