![](/img/trans.png)
[英]Java: Can I convert List of Object to List of String[] and vice versa?
[英]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.