stag-java icon indicating copy to clipboard operation
stag-java copied to clipboard

Add support for top-level json lists

Open brentwatson opened this issue 7 years ago • 1 comments

Issue Summary

A server response such as

[
  {},
  {}
]

maps to a model like:

public class Foo extends ArrayList<Bar> {}

stag fails generating code these top-level array objects.

Reproduction Steps

See above

Expected Behavior

Extending ArrayList should produce valid code

Actual Behavior

Fails to generate.

brentwatson avatar Oct 30 '17 18:10 brentwatson

Finally getting around to looking closely at this. In order to maintain parity with Gson, if a class implements the list interface or is an array, we will use the logic from Gson which serializes all lists and arrays the same way:

if (type instanceof GenericArrayType || type instanceof Class && ((Class<?>) type).isArray()) { 
    // return array adapter
}

then it will be serialized as a List or an Array and non of it's child properties will be serialized.

For example, given the following class:

@UseStag
class Test extends ArrayList<String> {
    @SerializedName("test_field")
    public String testField;
}

With this initialization:

final Test test = new Test();
test.add("one");
test.add("two");
test.add("three");
test.testField = "four";

The class will be serialized to:

[
 "one",
 "two",
 "three"
]

and as there is no way to represent a list with extra fields, only lists declared like above will be able to be parsed into objects that extend the List interface.

The easiest implementation would be to change ElementUtils.isSupportedElementKind to return false if the element implements the list interface or is an array. However, we can remove the need to do reflective instantiation if we modify StagProcessor.generateTypeAdapter to do the check instead. Then, an implementation of AdapterGenerator can be created that handles types that extend the list interface.

anthonycr avatar Jul 30 '18 21:07 anthonycr