0

Situation

I have a class that holds a generic type, and it also has a non-zero arg constructor. I don't want to expose a zero arg constructor because it can lead to erroneous data.

public class Geometries<T extends AbstractGeometry>{

    private final GeometryType geometryType;
    private Collection<T> geometries;

    public Geometries(Class<T> classOfT) {
        this.geometryType = lookup(classOfT);//strict typing.
    }

}

There are several (known and final) classes that may extend AbstractGeometry.

public final Point extends AbstractGeometry{ ....}
public final Polygon extends AbstractGeometry{ ....}

Example json:

{
    "geometryType" : "point",
    "geometries" : [
        { ...contents differ... hence AbstractGeometry},
        { ...contents differ... hence AbstractGeometry},
        { ...contents differ... hence AbstractGeometry}
    ]
}

Question

How can I write a JsonDeserializer that will deserialize a Generic Typed class (such as Geometires)?

CHEERS :)

p.s. I don't believe I need a JsonSerializer, this should work out of the box :)

Andrew
  • 33
  • 8

1 Answers1

0

Note: This answer was based on the first version of the question. The edits and subsequent question(s) change things.

p.s. I don't believe I need a JsonSerializer, this should work out of the box :)

That's not the case at all. The JSON example you posted does not match the Java class structure you apparently want to bind to and generate.

If you want JSON like that from Java like that, you'll definitely need custom serialization processing.

The JSON structure is

an object with two elements
    element 1 is a string named "geometryType"
    element 2 is an object named "geometries", with differing elements based on type

The Java structure is

an object with two fields
    field 1, named "geometryType", is a complex type GeometryType
    field 2, named "geometries" is a Collection of AbstractGeometry objects

Major Differences:

  1. JSON string does not match Java type GeometryType
  2. JSON object does not match Java type Collection

Given this Java structure, a matching JSON structure would be

an object with two elements
    element 1, named "geometryType", is a complex object, with elements matching the fields in GeometryType
    element 2, named "geometries", is a collection of objects, where the elements of the different objects in the collection differ based on specific AbstractGeometry types

Are you sure that what you posted is really what you intended? I'm guessing that either or both of the structures should be changed.

Regarding any question on polymorphic deserialization, please note that the issue was discussed a few times on StackOverflow.com already. I posted a link to four different such questions and answers (some with code examples) at Can I instantiate a superclass and have a particular subclass be instantiated based on the parameters supplied.

Community
  • 1
  • 1
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97