简体   繁体   English

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

[英]How to Deserialize a JSON and serialize a specific String value pair as different JSON?

The Json body I want to deserialize is something like below我要反序列化的 Json 主体如下所示

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

Below is the Json body I want to build from above Json after deserializing it下面是我想在反序列化后从上面构建的 Json 主体

{
"place_id": "07e0a63d862b2982e4c4b7e655f148d2"
}

Because your JSON data appears to be rather small you could use Gson's JsonParser.parseString(String) method to parse the data into an in-memory representation, then copy the relevant JSON object member to a new JsonObject and serialize that to JSON using Gson.toJson(JsonElement) :因为您的 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);

If this solution turns out to not be efficient enough for you, you could also have a look at JsonReader and JsonWriter .如果这个解决方案对你来说不够高效,你也可以看看JsonReaderJsonWriter

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

相关问题 如何反序列化特定的JSON字符串 - How to Deserialize specific JSON string 序列化.NET字典 <string, string> 到JSON键值对象 - Serialize .NET Dictionary<string, string> into JSON Key Value Pair Object WCF - 如何在JSON中序列化和反序列化? - WCF - How to serialize and deserialize in JSON? 如何序列化/反序列化字典 <string, int> ().OrderByDescending(kvp =&gt; kvp.Value)发送给Json? - How to serialize/deserialize Dictionary<string, int>().OrderByDescending(kvp => kvp.Value) to Json? 如何使用 JPA 和 Hibernate 自动序列化和反序列化 JSON 字符串? - How to automatically serialize and deserialize JSON string using JPA and Hibernate? 如何反序列化此特定的json字符串? - How can I deserialize this specific json string? 如何在没有键值对的情况下反序列化json? C# - How to deserialize json without key value pair? C# Jackson - 将属性序列化/反序列化为JSON值 - Jackson - serialize/deserialize property as JSON value Json.NET 反序列化或序列化 json 字符串并将属性映射到运行时定义的不同属性名称 - Json.NET deserialize or serialize json string and map properties to different property names defined at runtime 如果成对值是字符串,如何从json获取键和成对值 - How to get the key and pair value from json if the pair value as string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM