【问题标题】:Remove empty object from json array using GSON使用 GSON 从 json 数组中删除空对象
【发布时间】:2019-06-25 18:59:20
【问题描述】:
{
  "ChangeRequests": [
    {}
  ]
}

使用 Gson 从 JSON 数组中删除空模型。 因为它在模型的列表中创建了一个模型,所有值都为空,使用 Gson

data class TestRequest(
@SerializedName("ChangeRequests")
val changeRequests: List<ChangeRequest>

)

val result = Gson().fromJson(jsonString,TestRequest::class.java)

【问题讨论】:

    标签: android arrays json kotlin gson


    【解决方案1】:

    简单的代码:它对我有用!

    Type type = new TypeToken<Map<String, Object>>() {}.getType();
    Map<String, Object> data = new Gson().fromJson(jsonString, type);
    
    for (Iterator<Map.Entry<String, Object>> it = data.entrySet().iterator(); 
    it.hasNext();) {
    Map.Entry<String, Object> entry = it.next();
    if (entry.getValue() == null) {
        it.remove();
    } else if (entry.getValue().getClass().equals(ArrayList.class)) {
        if (((ArrayList<?>) entry.getValue()).size() == 0) {
            it.remove();
        }
     }
    }
    
    String json = new GsonBuilder().setPrettyPrinting().create().toJson(data);
    System.out.println(json);
    

    【讨论】:

    • 这是您在将 JSON 转换为模型后正在处理的。我想要的是 GsonBuilder 级别的东西。
    猜你喜欢
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多