Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify json with GSON without using a POJO

Tags:

java

json

gson

I want to modify a json content without converting it into a POJO. I am using GSON Library.

Following are the use case:

String jsonString = "[{\"key1\":\"Hello\",\"key2\":\"World\"},{\"key1\":\"Nice\",\"key2\":\"Town\"}]";

JsonElement jsonElement = gson.fromJson(jsonString, JsonElement.class);     

Is there any way where I can set value of key1 to some value (let say "Test") in each array, without converting things into POJO

like image 943
linuxeasy Avatar asked Jan 24 '13 10:01

linuxeasy


People also ask

Does Gson use getters and setters?

For now, Gson is fields-based. I don't think shouldn't use getters and setters, Chris Shaffer explains this pretty good in this answer. Write a custom serializer/deserializer, that way you can use whatever method you want to write the values back into your class.

What does Gson toJson do?

Introduction. Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.


1 Answers

Here's the shortest I came up with.

JsonElement je = new Gson().fromJson(jsonString, JsonElement.class);
JsonObject jo = je.getAsJsonObject();
jo.add("key", value);

Once you have the JsonObject, gson has many methods to manipulate it.

like image 101
Bruce Edge Avatar answered Sep 20 '22 05:09

Bruce Edge