【问题标题】:Jackson : Filter null or blank values while converting json string response to pojo conversion using jackson杰克逊:过滤空值或空白值,同时使用杰克逊将 json 字符串响应转换为 pojo 转换
【发布时间】:2012-11-15 02:22:59
【问题描述】:

我正在使用 jackson 将 jason 响应转换为 pojo 列表。以下是我收到的回复。

[

    {
        "code": "",
        "total": 24,
        "name": null
    },
    {
        "code": "",
        "total": 1,
        "name": "Test"
    }
]

我正在将其转换为 Pojo 列表。下面是我的pojo。

public class ItemCategory {

private String code;
private String name;
private String total;

public ItemCategory() {
}

public ItemCategory(final String code, final String name, final String total) {
    super();
    this.code = code;
    this.name = name;
    this.total = total;
}

/**
 * @return the code
 */
public String getCode() {
    return code;
}

/**
 * @param code
 *            the code to set
 */
public void setCode(final String code) {
    this.code = code;
}

/**
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * @param name
 *            the name to set
 */
public void setName(final String name) {
    this.name = name;
}

/**
 * @return the count
 */
public String getTotal() {
    return total;
}

/**
 * @param count
 *            the count to set
 */
public void setTotal(final String total) {
    this.total = total;
}
}

一切正常。但我想删除要转换为 pojo 的值,它的代码为空白/空值。即“代码”:“”,或“代码”:null

我正在使用下面的杰克逊代码将 json 转换为 pojo。

Object pojo = null;
try {
    pojo = mapper.readValue(jsonString, typeReference);
} catch (JsonParseException e) {
    throw new InvalidPojoException(e.toString(), e);
} catch (JsonMappingException e) {
    throw new InvalidPojoException(e.toString(), e);
} catch (IOException e) {
    throw new InvalidPojoException(e.toString(), e);
} catch (Exception e) {
    throw new InvalidPojoException(e.toString(), e);
}
return pojo;

使用下面的 json 代码来反对。

(List<ItemCategory>) JsonParserUtil.toPojo(serviceResponse.getStringResponse(),new TypeReference<List<ItemCategory>>(){});

任何指针将不胜感激。

提前致谢。

【问题讨论】:

  • 您介意将答案设置为已接受吗?谢谢:)

标签: json liferay jackson liferay-6 pojo


【解决方案1】:

您可能希望像这样注释您的 bean 类:

@JsonSerialize(
include=JsonSerialize.Inclusion.NON_NULL,
)

来源:JsonSerialize annotation javadoc

【讨论】:

  • 感谢米哈尔的回复。只是为了澄清它是否会简单地删除它具有空值的整个属性集。可以说,从我的问题中提到的响应来看,最终的序列化 List 不应包含第一个具有“total”:24 的对象,因为它的代码具有空白(“”)值。因此,该列表将仅包含一组对象,这些对象具有“代码”的非空值/空白值。和其他集合我不想被序列化到 ItemCategory pojo。所以我不想删除“code”属性本身,而是删除“code”的空值/空白值的整个集合。
  • 我不这么认为,不,因为,给定一个简单的空检查,列表元素本身不会为空。由于这是一个更复杂的情况,您可能应该为列表对象创建自己的序列化程序(我认为 ItemCategory 类本身的序列化程序就足够了)。
  • 谢谢米哈尔。它给了我一些前进的方向。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 2023-04-07
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
相关资源
最近更新 更多