Java – use gson to add an existing JSON string
•
Java
I have a string object that contains some arbitrary JSON I want to wrap it in another JSON object, like this:
{ version: 1,content: >>arbitrary_json_string_object<< }
How can I reliably add my JSON string as an attribute without having to build it manually (that is, avoid cumbersome string concatenation)?
class Wrapper { int version = 1; } gson.toJson(new Wrapper()) // Then what?
Note that the added JSON should not be escaped, but as part of the wrapper of a valid JSON entity, such as:
{ version: 1,content: ["the content",{name:"from the String"},"object"] }
given
String arbitraryJson = "[\"the content\",{name:\"from the String\"},\"object\"]";
Solution
This is my solution:
Gson gson = new Gson(); Object object = gson.fromJson(arbitraryJson,Object.class); Wrapper w = new Wrapper(); w.content = object; System.out.println(gson.toJson(w));
There I changed your wrapper class:
// setter and getters omitted public class Wrapper { public int version = 1; public Object content; }
If you want to hide the details of deserialization / serialization, you can also write a custom serializer for wrapper
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
二维码