json - 如何反序列化 JSON 并将特定的字符串值对序列化为不同的 JSON?
问题描述
我要反序列化的 Json 主体如下所示
{
"status": "OK",
"place_id": "07e0a63d862b2982e4c4b7e655f148d2",
"scope": "APP"
}
下面是我想在反序列化后从 Json 上方构建的 Json 主体
{
"place_id": "07e0a63d862b2982e4c4b7e655f148d2"
}
解决方案
因为您的 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);
如果这个解决方案对你来说不够高效,你也可以看看JsonReader
and JsonWriter
。
推荐阅读
- c++ - 为什么不打印矢量元素?
- vb.net - 无法将 WinForm 的 MinimumSize.Width 设置为大于 1278
- ruby-on-rails - 灵活的系统批量销毁每条记录
- javascript - 如何确保缩放不低于零并避免缩放点接触 y 和 z 轴?d3.zoom v4
- php - p标签中的h,i,b,u标签导致php出错
- multithreading - 多线程项目的 Big-O
- django - 如何在 django 模板中进行数学运算?
- java - FetchType.LAZY 不适用于休眠中的@ManyToOne 映射
- php - 如果数据值为空,如何不显示字符串数据?php
- java - Spring Boot、Gradle 和非 Maven 依赖项