My JSON
response:
{
"date": 1555044585641,
"changed": true,
"data": {
"items": [
{
"id": 503,
"activated": false,
"view": {
"listItem": {
...
},
"details": {
...
}
}
}
]
}
}
I am using below class to parse JSON
using Gson
:
public class Response {
@SerializedName("date")
public long date;
@SerializedName("changed")
public boolean changed;
@SerializedName("data")
public JsonObject data;
}
I save "data" part as a string using data.toString()
since data is JsonObject
. My question is:
How can I exclude "details" part before saving?
Saved string should look like:
{
"items": [
{
"id": 503,
"activated": false,
"view": {
"listItem": {
...
}
}
}
]
}
You need to traverse JSON
structure using JsonElement
, JsonArray
, 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");
}
}
});
}
}
After deserialisation invoke removeDetails()
and you can save only required data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.