简体   繁体   中英

Deserialize object using function in Jackson json

I have a function that produces an object. Would it be possible to deserialize this object using Jackson JSON annotations?

class Foo{
  Bar getBar(int par1, int par 2){
    ...
  }
  public static void main( String[] args )  {
    String json = "{\"par1\":1,\"par2\":2}";
    Bar bar = new ObjectMapper().<invoke function getBar>.readValue(json);
  }
}

One way you can do that is parsing this Json String to Jacksons JsonNode , and then invoke your method.

Something like this:

public static void main( String[] args )  {
    String json = "{\"par1\":1,\"par2\":2}";
    JsonNode jsonNode = new ObjectMapper().readValue(json, JsonNode.class);
    Bar bar = Foo.getBar(jsonNode.get("par1").asInt(), jsonNode.get("par2").asInt());
}

The possible solutiun is to add par1 and par2 to your Foo class. But don't forget to add @JSONIgnore to "get" methods which aren't usefull for json parsing.

class Foo{
  int par1;
  int par2;

  @JsonIgnore
  Bar getBar(){
     //..par1 par2 logic;
  }
  int getPar1(){
     return par1;
  }
  void setPar1(int par1) {
     this.par1=par1;
  }
  //same setter\getter for par2
}

And then you can simply parse JSON to this object and call Bar method

String json = "{\"par1\":1,\"par2\":2}";
Bar bar = new ObjectMapper().readValue(json,Foo.class).getBar();

You can tell Jackson to use a factory method or non default constructor using the @JsonCreator annotation. However, the method has to be part of the Class that is deserialized. So, assuming Bar has a two args constructor:

public class Bar {
  @JsonCreator
  public Bar (@JsonProperty("par1") int par1, @JsonProperty("par2") int par 2) {
    ...
  }
  public static void main( String[] args )  {
    String json = "{\"par1\":1,\"par2\":2}";
    Bar bar = (Bar)new ObjectMapper().readValue(json, Bar.class);
  }
}

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