[英]How to Deserialize a JSON and serialize a specific String value pair as different JSON?
我要反序列化的 Json 主體如下所示
{
"status": "OK",
"place_id": "07e0a63d862b2982e4c4b7e655f148d2",
"scope": "APP"
}
下面是我想在反序列化后從上面構建的 Json 主體
{
"place_id": "07e0a63d862b2982e4c4b7e655f148d2"
}
因為您的 JSON 數據看起來相當小,您可以使用 Gson 的JsonParser.parseString(String)
方法將數據解析為內存中的表示,然后將相關的 JSON 對象成員復制到新的JsonObject
並使用Gson.toJson(JsonElement)
將其序列化為 JSON Gson.toJson(JsonElement)
:
JsonObject original = JsonParser.parseString(json).getAsJsonObject();
JsonObject copy = new JsonObject();
// Might also have to add some validation to make sure the member
// exists and is a string
copy.add("place_id", original.get("place_id"));
String transformedJson = new Gson().toJson(copy);
如果這個解決方案對你來說不夠高效,你也可以看看JsonReader
和JsonWriter
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.