Your JSON model does not match your object model .
An intermediate level is required to fill the gap: TypeAdapter .
In addition, there is no name information for the user.
And finally, there is a name mismatch: "worklog" in JSON, "worklogs" in Java.
Here is the fixed version:
Java Model:
class User { private String timeSpent; @SerializedName("worklog") private List<WorkLog> worklogs = new LinkedList<WorkLog>(); private String name; public List<WorkLog> getWorklogs() { return worklogs; } public void setWorklog(List<WorkLog> worklogs) { this.worklogs = worklogs; } public String getTimeSpent() { return timeSpent; } public void setTimeSpent(String timeSpent) { this.timeSpent = timeSpent; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Plumbing to fill in the gap:
class BookTypeAdapter implements JsonSerializer<Book>, JsonDeserializer<Book> { Gson gson = new Gson(); public JsonElement serialize(Book book, Type typeOfT, JsonSerializationContext context) { JsonObject json = new JsonObject(); for (User user : book.getUser()) { json.addProperty(user.getName(), gson.toJson(user)); } return json; } public Book deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject json = element.getAsJsonObject(); Book book = new Book(); for (Entry<String, JsonElement> entry : json.entrySet()) { String name = entry.getKey(); User user = gson.fromJson(entry.getValue(), User.class); user.setName(name); book.getUser().add(user); } return book; } }
And the circuit:
GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Book.class, new BookTypeAdapter()); Gson gson = builder.create(); Book book = gson.fromJson("{" + " \"user1\": {" + " \"timeSpent\": \"20.533333333333335h\"," + " \"worklog\": [" + " {" + " \"date\": \"06/26/2013\"," + " \"issues\": [" + " {" + " \"issueCode\": \"COC-2\"," + " \"comment\": \"\ncccccc\"," + " \"timeSpent\": \"20.533333333333335h\"" + " }" + " ]," + " \"dayTotal\": \"20.533333333333335h\"" + " }" + " ]" + " }," + " \"admin\": {" + " \"timeSpent\": \"601.1h\"," + " \"worklog\": [" + " {" + " \"date\": \"06/25/2013\"," + " \"issues\": [" + " {" + " \"issueCode\": \"COC-1\"," + " \"comment\": \"\"," + " \"timeSpent\": \"113.1h\"" + " }" + " ]," + " \"dayTotal\": \"113.1h\"" + " }," + " {" + " \"date\": \"06/26/2013\"," + " \"issues\": [" + " {" + " \"issueCode\": \"COC-1\"," + " \"comment\": \"\"," + " \"timeSpent\": \"8h\"" + " }," + " {" + " \"issueCode\": \"COC-2\"," + " \"comment\": \"\"," + " \"timeSpent\": \"480h\"" + " }" + " ]," + " \"dayTotal\": \"488h\"" + " }" + " ]" + " }" + "}", Book.class); String json = gson.toJson(book);
Take a look at my tutorial to get an idea of ββwhat is possible with Gson: Mapping Java / JSON with Gson
Enjoy! :)