Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a POJO to JSON with GSON

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?

like image 672
MaikelS Avatar asked Jan 04 '12 10:01

MaikelS


People also ask

How do you convert POJO to JSON?

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.

How do you serialize an Object using Gson?

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.

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.


2 Answers

Pojo myPojo = new Pojo();

Gson gson = new Gson();
gson.toJson(myPojo);
like image 107
ŁukaszBachman Avatar answered Sep 22 '22 03:09

ŁukaszBachman


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));
like image 40
Ramiro Nahuel Acoglanis Avatar answered Sep 19 '22 03:09

Ramiro Nahuel Acoglanis