java – Serialize a POJO to JSON with GSON-ThrowExceptions

Exception or error:

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?

How to solve:
Pojo myPojo = new Pojo();

Gson gson = new Gson();


The gson.toJson() returns a String, not a JsonObject.

If you want to get a real JsonObject better do this:

JsonObject json = (JsonObject)parser.parse(new Gson().toJson(myPojo));

Leave a Reply

Your email address will not be published. Required fields are marked *