简体   繁体   English

将带有嵌入对象的 Java 对象转换为带有属性列表和值列表的 JSON,反之亦然

[英]Convert Java object with embedded objects to a JSON with list of attributes and list of values and vice versa

In my Spring project I have several objects that should be serialized to a specific JSON format.在我的 Spring 项目中,我有几个对象应该序列化为特定的 JSON 格式。

public class Person {
   private Integer id;
   private String name;
   private String height;
   private Address address;
}

and

public class Address {
   private String street;
   private String city;
   private String phone;
}

Let assume that Person.height and Address.phone should not appear in the JSON.假设 Person.height 和 Address.phone 不应该出现在 JSON 中。 The resulting JSON should look like生成的 JSON 应如下所示

{
  "attributes": ["id", "name", "street", "city"],
  "values": [12345, "Mr. Smith", "Main street", "Chicago"]
}

I can create create a standard JSON with an ObjectMapper and some annotations like @JsonProperty and @JsonUnwrapped where I disable some SerializationFeatures.我可以使用 ObjectMapper 和一些注释(如 @JsonProperty 和 @JsonUnwrapped)创建一个标准 JSON,其中我禁用了一些 SerializationFeatures。 But at the moment I'm not able to create such a JSON.但目前我无法创建这样的 JSON。

Is there an easy way to create this JSON?有没有一种简单的方法来创建这个 JSON? And how would the way back (deserialization) look like?回来的路(反序列化)会是什么样子?

There are good reasons Jackson doesn't serializes maps in this format. Jackson 不以这种格式序列化地图是有充分理由的。 It's less readable and also harder to deserialize properly.它的可读性较差,也更难正确反序列化。

But if you just create another POJO it's very easy to achieve what you want to do:但是,如果您只是创建另一个 POJO,那么很容易实现您想要做的事情:

public class AttributeList {

    public static AttributeList from(Object o) {
        return from(new ObjectMapper().convertValue(o, new TypeReference<Map<String, Object>>() {}));
    }

    public static AttributeList from(Map<String, Object> attributes) {
        return new AttributeList(attributes);
    }

    private final List<String> attributes;
    private final List<Object> values;

    private AttributeList(Map<String, Object> o) {
        attributes = new ArrayList<>(o.keySet());
        values = new ArrayList<>(o.values());
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM