问题描述
我要反序列化的Json主体如下所示
{
"status": "OK","place_id": "07e0a63d862b2982e4c4b7e655f148d2","scope": "APP"
}
下面是我要反序列化后从Json上方构建的Json主体
{
"place_id": "07e0a63d862b2982e4c4b7e655f148d2"
}
解决方法
由于您的JSON数据似乎很小,您可以使用Gson的JsonParser.parseString(String)
方法将数据解析为内存表示形式,然后将相关的JSON对象成员复制到新的JsonObject
并进行序列化使用Gson.toJson(JsonElement)
将其转换为JSON:
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
。