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

112 views Asked by At

The Json body I want to deserialize is something like below

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

Below is the Json body I want to build from above Json after deserializing it

{
"place_id": "07e0a63d862b2982e4c4b7e655f148d2"
}
1

There are 1 answers

0
Marcono1234 On

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):

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.