简体   繁体   English

使用GSON解析JSON对象列表

[英]Parse List of JSON objects using GSON

I have a JSON object like this: 我有一个像这样的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"
      }
    ]
  }
}

and trying to parse it with Gson: 并尝试用Gson解析它:

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

But the 'responceBean' is always 'null' 但'responceBean'总是'null'

Here are all the other classes: 以下是所有其他课程:

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

This is my latest attempt. 这是我最近的尝试。 Somehow I cannot figure out the right way. 不知怎的,我无法弄清楚正确的方法。 Will be very appreciative for any help. 对任何帮助都会非常感激。

Your JSON model does not match your object model . 您的JSON模型与您的对象模型不匹配

You need an intermediate layer to fill the gap: a TypeAdapter . 您需要一个中间层来填补空白: TypeAdapter

Moreover there is no naming information for the user. 此外,没有用户的命名信息。

And finally there is a name mismatch: "worklog" in JSON, "worklogs" in Java. 最后有一个名称不匹配:JSON中的“worklog”,Java中的“worklogs”。

Here is a fixed version: 这是一个固定版本:

Java model: 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;
    }
}

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 看看我的教程,了解Gson的可能性:使用Gson进行Java / JSON映射

Enjoy! 请享用! :) :)

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. 试试这个,我希望它会有所帮助。

PS Also as Erik Pragt said you have array of Users, not just single one. PS另外,Erik Pragt说你有一系列用户,而不仅仅是单一用户。 So you will have to make 1 more class that contains a List < Users >. 因此,您将需要再创建一个包含List <Users>的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM