使用GSON解析JSON对象列表

时间:2013-06-26 13:45:27

标签: java json parsing gson

我有一个像这样的JSON对象:

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

并尝试用Gson解析它:

Gson gson = new Gson();
Book responseBean = gson.fromJson(jsonString, Book.class);

但'responceBean'始终为'null'

以下是所有其他课程:

public class Book {

    private List<User> user = new LinkedList<User>();

    public List<User> getUser() {
        return user;
    }

    public void setUser(List<User> user) {
        this.user = user;
    }
}

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

    public List<WorkLog> getWorklogs() {
        return worklogs;
    }

    public void setWorklogs(List<WorkLog> worklogs) {
        this.worklogs = worklogs;
    }

    public String getTimeSpent() {
        return timeSpent;
    }

    public void setTimeSpent(String timeSpent) {
        this.timeSpent = timeSpent;
    }
}

public class WorkLog{
    private String date;
    private String dayTotal;
    private List<Issues> issues;

    public String getDate(){
        return this.date;
    }
    public void setDate(String date){
        this.date = date;
    }
    public String getDayTotal(){
        return this.dayTotal;
    }
    public void setDayTotal(String dayTotal){
        this.dayTotal = dayTotal;
    }
    public List<Issues> getIssues(){
        return this.issues;
    }
    public void setIssues(List<Issues> issues){
        this.issues = issues;
    }
}

public class Issues{
    private String comment;
    private String issueCode;
    private String timeSpent;

    public String getComment(){
        return this.comment;
    }
    public void setComment(String comment){
        this.comment = comment;
    }
    public String getIssueCode(){
        return this.issueCode;
    }
    public void setIssueCode(String issueCode){
        this.issueCode = issueCode;
    }
    public String getTimeSpent(){
        return this.timeSpent;
    }
    public void setTimeSpent(String timeSpent){
        this.timeSpent = timeSpent;
    }
}

这是我最近的尝试。不知怎的,我无法弄清楚正确的方法。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:10)

您的 JSON模型与您的对象模型不匹配。

您需要一个中间层来填补空白: TypeAdapter

此外,用户没有命名信息。

最后有一个名称不匹配:JSON中的“worklog”,Java中的“worklogs”。

这是一个固定版本:

Java模型:

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

填补空白的管道:

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

往返:

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

查看我的教程,了解Gson的可能性: Java/JSON mapping with Gson

享受! :)

答案 1 :(得分:0)

我在一个月之前遇到了一些问题。据我所知,这是因为和你一样,我忘了对物体做“新”。我的意思是它应该看起来:

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

试试这个,我希望它会有所帮助。

P.S。 另外,正如Erik Pragt所说,你拥有一系列用户,而不仅仅是单一用户。因此,您将需要再创建一个包含List&lt;的类。用户&gt;。