Question

I have following data structure:

Class UserModel {
Long pkid;
String name;
public UserModel() {
this.pkid = new Long(1001);
this.name = "ABC";
}
}

Now I have converted this into json:

UserModel usrObj = new UserModel();
Gson gson = new Gson();
String json = gson.toJson(userObj);

So my json string is now like:

{  "pkid": 1001,
    "name": "ABC" }

But I need to create the json as

{"com.vlee.ejb.UserModel": [
{  "pkid": 1001,
    "name": "ABC" } ] }

I can easily create a json like:

{"userModel": [
{  "pkid": 1001,
        "name": "ABC" } ] }

When I am facing problem to create an index using dot.

I am not sure how I can add the key "com.vlee.ejb.UserModel"

Was it helpful?

Solution

    UserModel userObj = new UserModel();
    HashMap map = new HashMap();
    ArrayList array = new ArrayList();
    array.add(userObj);
    map.put(userObj.getClass().getName(), array);
    Gson gson = new Gson();
    String json = gson.toJson(map);
    System.out.println(json);

and it output: {"com.vlee.ejb.UserModel":[{"pkid":1001,"name":"ABC"}]}

OTHER TIPS

Create a serializer class to customize the output. This will likely involve creating and arranging a few JsonElement subclass instances. In this case, you'd make a JsonObject with a JsonArray as one of its values, which in turn contains a JsonObject with the "pkid" and "name" stuff in it.

Assuming you'd want to be able to read these objects back in, the same class can also implement the deserialization interface, in which case it would be given a JsonElement instance and have to pick it apart to construct the desired Java object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top