Jackson Deserialiser:在场上使用@JsonCreator和@JsonProperty?

时间:2017-10-10 08:47:06

标签: java json jackson2

我正在尝试将一些Json解析为Java对象 某些字段需要自定义行为,因此我尝试在构造函数上使用@JsonCreator

嗯,它有效,但是对于其他字段,注释@JsonProperty没有填充 还没有检查,但我想我的对象注释@JsonUnwrapped也没有填充。

在我的搜索中,我看到一条评论表明它是可能的,但如果确实可能,我无法弄清楚。

json中有大约400个字段,只有5个或6个需要自定义行为。所以,如果我可以避免重写所有构造函数...这将是很好的!

我尝试过的例子:

public class MyObjectA {

  @JsonProperty("keyField1")
  private String myField1;

  @JsonUnwrapped
  private MyObjectB;

  private String[] myField2;

  @JsonCreator
  public MyObjectA(final Map<String, Object> properties){

    myField2  = ... //some Business logic 

  }

}

Junit:

ObjectMapper mapper = new ObjectMapper();
MyObjectA result = mapper.readValue(getJsonInputStream(JSON_FILE_PATH),MyObjectA.class);
Assert.notNull(result.getMyField1(),"should be populated")
Assert.notNull(result.getMyField2(),"should be populated")
Assert.notNull(result.getMyObjectB(),"should be populated")

注意:没有构造函数,其他字段填充良好

1 个答案:

答案 0 :(得分:1)

在这里。查看注释和非注释@JsonConstructor用法之间的区别。我正在处理属性作为自定义处理,并使用setName调用名称。希望有所帮助

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;

public class Jackson2 {


    public static void main(String[] args) throws Exception {

        final ObjectMapper mapper = new ObjectMapper();
        final String jsonInString = "{\"name\":\"hello world\",\"something\":\"from string\"}";
        System.out.println(jsonInString);

        Foo newFoo = mapper.readValue(jsonInString, Foo.class);
        System.out.println(newFoo.getName());
        System.out.println(newFoo.getSomething());
    }
}

class Foo {

    @JsonProperty
    private String name;
    private String something;

    public String getSomething() {
        return something;
    }

    public void setSomething(String something) {
        this.something = something;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;

    }

    Foo() {
    }

  // @JsonCreator
    public Foo(final Map<String, Object> properties) {
            System.out.println("printing.."+properties);
            something =  "Something from constructor";
     }
    @JsonCreator
    public Foo(@JsonProperty("something") String something ) {
            System.out.println("printing.."+name);
            this.something =  "Something from constructor appended"+something;
    }



}

因此,想法是在构造函数参数中使用@JsonProperty来定制要自定义的属性。 :)