用杰克逊创建扁平对象形式嵌套json

9 java json jackson

我知道杰克逊允许创建平面json使用@JsonUnwrapped类似的对象

public class Person {
    public int age;
    @JsonUnwrapped public Name name;

    public class Name {
        public String first, last;
    }
}
Run Code Online (Sandbox Code Playgroud)

将被序列化

{"age" : 99, "first" : "Name", "last" : "Surname"}
Run Code Online (Sandbox Code Playgroud)

但是,我找不到相反的方法 - 有一个类似的

public class Person {
    public int age;
    public String firstName, lastName;
}
Run Code Online (Sandbox Code Playgroud)

并将其对象序列化并反序列化

{"age" : 99, "name" : {"first" : "Name", "last" : "Surname"}}
Run Code Online (Sandbox Code Playgroud)

这可能使用Jackson 1.9吗?

sfu*_*ger 6

我偶然发现了这个相当古老的问题.我最终这样做了:

public class Person {
  public int age;

  @JsonIgnore
  public String firstName, lastName;

  protected void setName(PersonName name) {
    firstName = name.first;
    lastName = name.last;
  }

  protected PersonName getName() {
    return new PersonName(firstName, lastName);
  }

  protected static class PersonName {
    private final String first, last;

    @JsonCreator
    public PersonName(@JsonProperty("first") String first, @JsonProperty("last") String last) {
      this.first = first;
      this.last = last;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)