用杰克逊创建扁平对象形式嵌套json [英] Creating flat object form nested json with Jackson

查看:156
本文介绍了用杰克逊创建扁平对象形式嵌套json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that Jackson allows to create flat json using @JsonUnwrapped so that object of a class like

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

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

将被序列化为

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

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

however, I can't find a way to do the opposite - have a class like

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

并将其对象序列化并从

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

这是否可以使用Jackson 1.9?

Is this possible using Jackson 1.9?

推荐答案

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

I stumbled upon this rather old question as I was looking for the same. I ended up doing this:

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

这篇关于用杰克逊创建扁平对象形式嵌套json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆