![](/img/trans.png)
[英]How to deserialize this dynamic keys JSON to Java custom Pojo using Jackson
[英]How can I deserialize a JSON array of “name” “value” pairs to a Pojo using Jackson
我想反序列化以下JSON對象:
{
"id":"001",
"module_name":"Users",
"name_value_list":
{
"user_name": {"name":"user_name", "value":"admin"},
"full_name": {"name":"full_name", "value":"Lluís Pi"},
"city": {"name":"full_name", "value":"Barcelona"},
"postal_code": {"name":"postal_code", "value":"08017"},
...
}
}
變成這樣的一些Java對象:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE)
public class UserEntry
{
private String id;
private String moduleName;
private Person nameValueList;
public String getId()
{
return id;
}
public String getModuleName()
{
return moduleName;
}
public Person getPerson()
{
return nameValueList;
}
}
其中Person是以下類別:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE)
class Person
{
private String userName;
private String fullName;
private String city;
private String postalCode;
}
使用傑克遜,但我得到反序列化錯誤。
如果我將字段nameValueList
的類型更改為Map,則所有反序列化過程都沒有問題,並且得到了一個映射,其中鍵是“名稱”值,而值是“值”值。
所以我的問題是:有沒有簡單的方法,或者沒有這么簡單的方法,可以將這種JSON對象反序列化為具有屬性prop_1
, prop_2
, prop_3
和prop_4
的Java Pojo?
{
"name_value_list":
{
"prop_1": {"name":"prop_1", "value":"value_1"},
"prop_2": {"name":"prop_2", "value":"value_2"},
"prop_3": {"name":"prop_3", "value":"value_3"},
"prop_4": {"name":"prop_4", "value":"value_4"},
...
}
}
不是很簡單,也不是很干凈。 但是,您可以通過為Person類中的JSON屬性實現一個與 setUser字段不匹配的UserEntry POJO屬性來實現此目的。
@JsonAnySetter
public void putUserField(String userKey, Map<String, String> userValue)
throws NoSuchFieldException {
String actualFieldName = getActualFieldName(userKey);
Field field = this.getClass().getDeclaredField(actualFieldName);
field.setAccessible(true);
ReflectionUtils.setField(field, this, userValue.get("value"));
}
private String getActualFieldName(String userKey) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, userKey);
}
除此之外,我還必須將Person類的Jackson屬性更改為
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY,
getterVisibility = JsonAutoDetect.Visibility.NONE)
它可以用於諸如“ city”之類的屬性,這些屬性不需要任何名稱轉換,因為jackson嘗試直接設置失敗的字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.