1

I have a class Item like this

class Item {
   private String name;
   private int age;
   private boolean gender;
}

and a class which contains this Item class ListItem { private List items; }

When using gson to generate to JSON, it will return something like this

[{"name": "a", "age": "a1", "gender": "male"}, {"name": "b", "age": "b1", "gender": "female"}, ...]

but I want to customize (without changing the POJO class as I could not do this) and in method

List<Item> listItems = new ArrayList<Item>();
listItems.add(new Item("a", "a1", "male");
listItems.add(new Item("b", "b1", "female");

Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(listItems);

then jsonElement will generate in to JSON string a structure like this (list of objects and with "name": "object")

{ 
   "a": { "name": a, "age": "a1", "gender": "male" },
   "b": { "name": b, "age": "b1", "gender": "female"}
}

when I serialize it

String json = gson.toJson(jsonElement);

1 Answer 1

1

Actually I can just change from

List<Item> to HashMap<String, Item>

then gson will generate this structure for me correctly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.