Hi, I'm having problem trying to serialize a group of object when using generics and wanted a little help to find what could I be doing wrong.

I've created an example that represent the same structure of objects im using to show my problem

Classes to serialize/deserialize

Class Diagram

Container class:

public class Container {
  @JSON
  private List<TestClassA> elements;

  public List<TestClassA> getElements() {
      return elements;
  }

  public void setElements(List<TestClassA> elements) {
      this.elements = elements;
  }
}

TestClassA:

public abstract class TestClassA<T extends TestInterface> {
  private T data;

  public TestClassA() {
  }

  public TestClassA(T data) {
      this.data = data;
  }

  public T getData() {
      return data;
  }

  public void setData(T data) {
      this.data = data;
  }
}

The rest of the classes are empty and are declared only for the example.

I can serialize a container object with no problems and I get a perfectly valid JSON:

JSONSerializer jss
       = new JSONSerializer()
         .prettyPrint(true);

Container c = new Container();
    c.setElements(
            (List)
            Arrays.asList(
                    new TestClassB(
                            new TestInterfaceImplA()),
                    new TestClassC(
                            new TestInterfaceImplA())));

String result = jss.serialize(c);

Result JSON:

{
  "class": "jsontest.Container",
  "elements": [
    {
        "class": "jsontest.TestClassB",
        "data": {
            "class": "jsontest.TestInterfaceImplA"
        }
    },
    {
        "class": "jsontest.TestClassC",
        "data": {
            "class": "jsontest.TestInterfaceImplA"
        }
    }
  ]
}

But when I try to deserialize this same JSON I get an InstantationException exception:

JSONDeserializer<Container> jsd
            = new JSONDeserializer();

Container desObj = jsd.deserialize(result);

Exception ():

Exception in thread "main" flexjson.JSONException: [ elements.values.data ]:There was an exception trying to instantiate an instance of jsontest.TestClassA
at flexjson.factories.BeanObjectFactory.instantiate(BeanObjectFactory.java:19)
at flexjson.ObjectBinder.bind(ObjectBinder.java:95)
at flexjson.ObjectBinder.bindIntoObject(ObjectBinder.java:149)
    .
    .
    .

The problem I cant understand is why the exception is thrown in 'elements.values.data' when data is an attribute of TestClassA of type TestInterface and is not related in any way to TestClassA.
The problem gets solved if I throw away the generic declaration and use a TestInterface as type for 'data' directly but that will reduce my code legibility at long run.

Regards.
Hernan.

 

Last edit: Hernan Pablo Keena 2014-12-15