I pull in some JSON, deserialize it to a POJO, edit some properties of the object, and now I want to serialize it back to JSON with GSON and send it back.
How do i serialize a javabean to JSON with GSON?
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
Serialization – Write JSON using Gson Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object. Program output.
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.
Pojo myPojo = new Pojo();
Gson gson = new Gson();
gson.toJson(myPojo);
The gson.toJson() returns a String, not a JsonObject.
If you want to get a real JsonObject better do this:
JSONParser parser = new JSONParser();
JsonObject json = (JsonObject)parser.parse(new Gson().toJson(myPojo));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With