How to use Gson convert Java object to Json String (serialize POJO) with root value included

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

If you are using Gson library (google-gsonA Java library to convert JSON to Java objects and vice-versa) and you want to serialize POJO with root value included like the following illustrated code for serializing XML.

@XmlRootElement
class Person implements Serializable {
    private String firstname;
    private String lastname;
    public Person() {
    firstname="firstname";
    lastname="lastname";
   }
}
......

It’s very simple, here is an example to do it with Gson:

    Gson gson = new Gson();
    JsonElement je = gson.toJsonTree(new Person());
    JsonObject jo = new JsonObject();
    jo.add("PersonRoot",je);

Leave a Reply

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