簡體   English   中英

將帶有嵌入對象的 Java 對象轉換為帶有屬性列表和值列表的 JSON,反之亦然

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

在我的 Spring 項目中,我有幾個對象應該序列化為特定的 JSON 格式。

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

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

假設 Person.height 和 Address.phone 不應該出現在 JSON 中。 生成的 JSON 應如下所示

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

我可以使用 ObjectMapper 和一些注釋(如 @JsonProperty 和 @JsonUnwrapped)創建一個標准 JSON,其中我禁用了一些 SerializationFeatures。 但目前我無法創建這樣的 JSON。

有沒有一種簡單的方法來創建這個 JSON? 回來的路(反序列化)會是什么樣子?

Jackson 不以這種格式序列化地圖是有充分理由的。 它的可讀性較差,也更難正確反序列化。

但是,如果您只是創建另一個 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