Search code examples
javajsonjacksondeserializationfasterxml

"no suitable constructor" error when deserializing JSON children


I'm trying to map a json structure to a pojo using fasterxml/jackson.

My json comes from a file and looks like this:

{
   "groups": [
      {
         "name": "Group1",
         "icon": "group1.png",
         "banner": "banner.png"
      },
      {
         "name": "Group2",
         "icon": "group2.png",
         "banner": "banner.png"
      }
   ],
   "ticker": [
      {
         "title": "ticker1",
         "description": "description",
         "url": "bla",
         "icon": "icon.png",
         "banner": "banner.png",
         "group": "Group1",
         "enabled": "true",
         "startTime": "00:00",
         "startDate": "15.10.2013"
      }
   ]
}

I'm interested in the groups. Therefore I created a class Groups:

public class Groups implements Serializable {
  private final static long serialVersionUID = 42L;

  private List<Group> groups;

  public Groups() {}

  public Groups ( List<Group> groups ) {
    this.groups = groups;
  }

  public List<Group> getGroups() {
    if (groups == null) {
        groups = new ArrayList<Group>();
    }
    return groups;
  }

  public void add(Group group) {
    getGroups().add(group);
  }
}

Usually I am using this code to map a json to a pojo:

public static <T> T readJsonFile(File file, Class<T> valueType) throws IOException {
    String json = readJsonFile(file.getAbsolutePath());
    if( StringUtils.isEmpty(json) ) {
        return null;
    }
    return createObjectMapper().readValue(json, valueType);
}

This works fine if the pojo is the outer json object. But if I am trying to extract the groups it fails with: "no suitable constructor".

How is it possible to extract a pojo that is nested in a json structure?


Solution

  • public Groups() {
        groups = new ArrayList<>();
    }
    

    The default constructor is used on serialization, and groups is just defined as interface.

    I would even change all, and initialize the field to a non-null value.