如何使用Jackson将“名称”“值”对的JSON数组反序列化为Pojo

时间:2014-01-22 15:58:03

标签: java json jackson deserialization

我想反序列化以下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;
}

使用Jackson,但我收到了反序列化错误。

如果我将字段nameValueList的类型更改为Map,则所有反序列化过程都没有问题,我得到一个映射,其中键是“name”值,值是“value”值。

所以我的问题是:是否有任何简单或没有这么简单的方法将这种JSON对象反序列化为具有属性prop_1prop_2prop_3的Java Pojo和prop_4

{
  "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"},
      ...
    }
}

1 个答案:

答案 0 :(得分:0)

不是很简单也不是很干净。但是,您可以通过为Person类中的JSON属性实现任何 setter字段来执行此操作,该字段与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试图直接设置失败的字段。