Java – use gson to modify JSON instead of POJO

I want to modify a JSON content without converting it to POJO I am using gson library

The following are use cases:

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

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

Is there any way to set the value of key1 to a certain value (that is, "test") in each array instead of converting it to POJO

Solution

This is the shortest I can think of

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

Once you have jsonobject, gson has many ways to manipulate it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>