如何使用Gson删除Json对象的嵌套字段

时间:2019-04-12 06:13:35

标签: java json gson

我的JSON回复:

{
    "date": 1555044585641,
    "changed": true,
    "data": {
        "items": [
            {
               "id": 503,
                "activated": false,
                "view": {
                    "listItem": {
                        ...
                    },
                    "details": {
                        ...
                    }
                }       
            }
        ]
    }
}

我正在使用下面的类通过JSON来解析Gson

public class Response {

    @SerializedName("date")
    public long date;

    @SerializedName("changed")
    public boolean changed;

    @SerializedName("data")
    public JsonObject data;
}

由于数据为data.toString(),因此我使用JsonObject将“数据”部分另存为字符串。我的问题是:

如何在保存之前排除“细节”部分?

保存的字符串应类似于:

{
    "items": [
        {
           "id": 503,
            "activated": false,
            "view": {
                "listItem": {
                    ...
                }
            }       
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

您需要使用JSONJsonElementJsonArray遍历JsonObject结构:

class Response {

    @SerializedName("date")
    public long date;

    @SerializedName("changed")
    public boolean changed;

    @SerializedName("data")
    public JsonObject data;

    public void removeDetails() {
        JsonElement items = data.get("items");
        if (!items.isJsonArray()) {
            return;
        }
        JsonArray array = items.getAsJsonArray();
        array.forEach(item -> {
            if (item.isJsonObject()) {
                JsonObject node = item.getAsJsonObject();
                JsonElement view = node.get("view");
                if (view.isJsonObject()) {
                    view.getAsJsonObject().remove("details");
                }
            }
        });
    }
}

反序列化后调用removeDetails(),您只能保存所需的数据。