Parse List of JSON objects using GSON

后端 未结 2 925
旧时难觅i
旧时难觅i 2021-01-03 07:14

I have a JSON object like this:

{
  \"user1\": {
    \"timeSpent\": \"20.533333333333335h\",
    \"worklog\": [
      {
        \"date\": \"06/26/2013\",
            


        
相关标签:
2条回答
  • 2021-01-03 07:21

    I had some problem before a month. As far as I remember it was because, same as you, I forgot to make "new" to objects. I mean that it should look:

    public class User {
        private String timeSpent;
        private List<WorkLog> worklogs = new List < WorkLog >();
    }
    

    Try this and I hope that it will help.

    P.S. Also as Erik Pragt said you have array of Users, not just single one. So you will have to make 1 more class that contains a List < Users >.

    0 讨论(0)
  • 2021-01-03 07:39

    Your JSON model does not match your object model.

    You need an intermediate layer to fill the gap: a TypeAdapter.

    Moreover there is no naming information for the user.

    And finally there is a name mismatch: "worklog" in JSON, "worklogs" in Java.

    Here is a 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;
        }
    }
    

    The plumbing to fill 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 a roundtrip:

    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);
    

    Have a look at my tutorial to get an idea of what is possible with Gson: Java/JSON mapping with Gson

    Enjoy! :)

    0 讨论(0)
提交回复
热议问题