java - 使用 GSON 解析 JSON 对象列表

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

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

最佳答案

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

您需要一个中间层来填补空白:a 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

尽情享受吧! :)

关于java - 使用 GSON 解析 JSON 对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17321828/

相关文章:

javascript getElementsByTagName 排除某些标签

java - 中断异常捕获中的方法调用是否会完成 run() 方法并使线程完成

python - 如何更改 JSON 文件中的嵌套值?

json - 以 Map<String, dynamic> 作为正文的 Dart HTTP POST

parsing - yocto食谱中的目标类别和 native 类别之间的差异

c++ - boost spirit qi 整数和 float 的数值解析

java - 线程 "main"StackoverFlow 错误中的异常

java - C3P0 一台服务器多个数据库

java - 比较流口水中的日期

mysql - 无法使用 JSON_CONTAINS 进行搜索