首页 > 解决方案 > 如何反序列化 JSON 并将特定的字符串值对序列化为不同的 JSON?

问题描述

我要反序列化的 Json 主体如下所示

{
"status": "OK",
"place_id": "07e0a63d862b2982e4c4b7e655f148d2",
"scope": "APP"
}

下面是我想在反序列化后从 Json 上方构建的 Json 主体

{
"place_id": "07e0a63d862b2982e4c4b7e655f148d2"
}

标签: jsonserializationgsonjson-deserializationjackson-databind

解决方案


因为您的 JSON 数据看起来相当小,您可以使用 Gson 的JsonParser.parseString(String)方法将数据解析为内存表示,然后将相关的 JSON 对象成员复制到一个新对象JsonObject并使用以下方法将其序列化为 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);

如果这个解决方案对你来说不够高效,你也可以看看JsonReaderand JsonWriter


推荐阅读