0

In my REST application I am using fasterxml to serialize and deserialize POJOs to JSON. I run into problems with collections such as List in a case like this.

public class JsonRequest {
    public int anumber;
    public String astring;
    public List<XyzClass> data;
}

The properties anumber and astring convert back and forth just fine without any annotations. For **data*, although the compiler can see that the List elements are (should be) XyzClass that information is not available to the jackson framework, so it doesn't know what class to use when deserializing the elements.

For some reason I can't make sense of the documentation as to which annotation to use to fix this. The @JsonDeserialize annotation doesn't help this. Can anyone point me in the right direction?

Amit
  • 30,756
  • 6
  • 57
  • 88
AlanObject
  • 9,613
  • 19
  • 86
  • 142
  • It is supported by default by Jackson, there is no need of explicit annotation to use. So, as per my understanding, it should work. Can u show your REST API code where you are `serializing` or `deserializing` this list – Vikas Sachdeva Apr 29 '17 at 07:50
  • can you provide the code of your XYZclass as well ? and how you are using JsonRequest in your resource class ? – Amit Apr 29 '17 at 16:40

1 Answers1

1

After some research I finally found out how to make this work.

public class JsonRequest {
    public int anumber;
    public String astring;
    @JsonDeserialize(contentAs = XyzClass.class) // <-- Added    
    public List<XyzClass> data;
}

To answer the questions in comments above, the code for XyzClass is just a trivial POJO like:

public class XyzClass {
    public String name;
    public int age;
}

What was tripping me up is that I was looking for an annotation to the effect of @JsonDeserializeContentAs(class = XyzClass.class) which doesn't exist because I missed the fact that @JsonDeserilize had a contentAs option.

Hopefully this posting will save someone else the same trouble.

AlanObject
  • 9,613
  • 19
  • 86
  • 142