繁体   English   中英

如何反序列化 JSON 并将特定字符串值对序列化为不同的 JSON?

[英]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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM