5

I have a object which uses a org.apache.commons.collections.list.LazyList for one of its fields, which is serialized ti JSON. The JSON looks like this:

        "myObject": ["org.apache.commons.collections.list.LazyList", [
            {
                "attr1": "asdasd",
                "attr2": 1234
            }
        ]],

The object field looks like this:

List<MyObject> myObject = ListUtils.lazyList(new ArrayList(), {new MyObject()} as Factory)

However trying to deserialize the above JSON using a Jackson ObjectMapper fails, since it can't find a default constructor for a LazyList - which makes sense. But how can I specify how this field can be deserialized?

Error message:

No default constructor for [collection type; class org.apache.commons.collections.list.LazyList, contains [simple type, class foo.bar.MyObject]]

Bounty-constraints:

To collect the bounty, this question needs to be answered using a custom jackson deserializer - the custom deserializer must not be field specific! Hence no solution using custom implementations of a LazyList for a specific type will answer this question adequately.

Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
Hoof
  • 1,738
  • 2
  • 17
  • 39
  • You should include the bounty text to the question, since it's relevant to properly answering it. – Peter O. Jul 10 '13 at 19:26
  • There is no way to make this 100% compatible with everything. Since data is lost, you must make assumptions, such as the LazyList's backing List implementation and factory. The only way to do this without making those assumptions is to add that information to the serialized JSON somehow. You can write your own serializer to use reflection to add that information, and deserializer to use that information to (again, using reflection) create the LazyList object, but you are still making assumptions, such as that your factories have 0-arg constructors. – Shadow Man Jul 10 '13 at 20:01
  • Do a google search for "java reflection" and use that to get the protected `collection` and `factory` variables for your serializer and the constructors for your deserializer. Or see other questions for help, such as: http://stackoverflow.com/questions/735230/java-reflection – Shadow Man Jul 10 '13 at 20:10

1 Answers1

1

The solution below worked on both List and Map collection objects, it might also work on yours.

@JsonDeserialize(contentAs=MyObject.class)
private List<MyObject> myObject = ListUtils.lazyList(new ArrayList(), {new MyObject()} as Factory);
jjcosare
  • 1,463
  • 9
  • 9