Search code examples
androidjsongsondatamodel

How to add an index in json data?


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"


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"}]}