简体   繁体   中英

Jackson JSON deserialization - synthetic list getter

I'm trying to use Jackson to deserialize some JSON originally created using Jackson. The model has a synthetic list getter:

public List<Team> getTeams() {
   // create the teams list
}

where the list is not a private member, but generated on the fly. Now this serialises fine, but in deserialization uses getTeams, presumably because Jackson sees a getter with a mutable list and thinks it can use it as a setter. The internals of getTeams rely on other fields which Jackson hasn't yet populated. The result of which is a NPE ie I think order is one of the problems here but not one I want to solve.

So, what I'd like to do is annotate getTeams so that it's never used as a setter but is used as a getter. Is this possible? Any suggestions?

Disable DeserializationConfig.Feature.USE_GETTERS_AS_SETTERS .

mapper.configure(DeserializationConfig.Feature.USE_GETTERS_AS_SETTERS, false);

Use static import to make this line shorter.

Or, if you want an annotation to just configure things for this one property, and not specify the global setting as above, then mark something as the setter for "teams".

public class Foo
{
  @JsonSetter("teams")
  public void asdf(List<Team> teams)
  {
    System.out.println("hurray!");
  }

  public List<Team> getTeams()
  {
    // generate unmodifiable list, to fail if change attempted
    return Arrays.asList(new Team());
  }

  public static void main(String[] args) throws Exception
  {
    ObjectMapper mapper = new ObjectMapper();
    String fooJson = mapper.writeValueAsString(new Foo());
    System.out.println(fooJson);
    // output: {"teams":[{"name":"A"}]}

    // throws exception, without @JsonSetter("teams") annotation
    Foo fooCopy = mapper.readValue(fooJson, Foo.class);
    // output: hurray!
  }
}

class Team
{
  public String name = "A";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM