【问题标题】:Creating flat object form nested json with Jackson使用 Jackson 创建平面对象形式的嵌套 json
【发布时间】:2014-03-12 01:37:51
【问题描述】:

我知道 Jackson 允许使用 @JsonUnwrapped 创建平面 json,以便类的对象像

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

    public class Name {
        public String first, last;
    }
}

会被序列化成

{"age" : 99, "first" : "Name", "last" : "Surname"}

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

public class Person {
    public int age;
    public String firstName, lastName;
}

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

{"age" : 99, "name" : {"first" : "Name", "last" : "Surname"}}

这可以使用 Jackson 1.9 吗?

【问题讨论】:

  • 据我所知没有。整个 wrapped 概念对于封装类/对象(例如 Name)会更有意义。
  • 是的,我认为你需要一个 Name 对象来保存第一个和最后一个
  • 太令人失望了,还是谢谢你...像@JsonProperty("name.first") public String firstName; 这样的东西会很棒...

标签: java json jackson


【解决方案1】:

我在寻找同样的问题时偶然发现了这个相当古老的问题。我最终这样做了:

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;
    }
  }
}

【讨论】:

  • 有没有最简单的解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-21
相关资源
最近更新 更多