使用GSON解析JSON对象的列表 [英] Parse List of JSON objects using GSON

查看:139
本文介绍了使用GSON解析JSON对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个JSON对象:

  {
user1:{
timeSpent:20.533333333333335h,
worklog:[
{
date:06/26/2013,
issues:[
{
issueCode:COC-2,
comment:\\\
cccccc,
timeSpent:20.533333333333335h
}
],
dayTotal:20.533333333333335h
}
]
},
admin:{
timeSpent:601.1 h,
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 = new LinkedList< User>();

公共列表<用户> getUser(){
返回用户;
}

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

public class User {
private String timeSpent;
私人列表< WorkLog> worklogs = new LinkedList< WorkLog>();;

公共列表< WorkLog> getWorklogs(){
返回工作日志;
}

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

public String getTimeSpent(){
return timeSpent;
}

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

公共类工作日志{
私人字符串日期;
private String dayTotal;
私人列表<问题>问题;

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<问题> getIssues(){
return this.issues;
}
public void setIssues(List< Issues> issues){
this.issues = issues;
}
}

公共类问题{
私人字符串评论;
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模型与您的对象模型不匹配

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



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



最后,名称不匹配:JSON中的worklog,Java中的worklogs。



下面是一个固定版本:



Java模型:

  class User {
private String timeSpent;
@SerializedName(worklog)
private List< WorkLog> worklogs = new LinkedList< WorkLog>();
私人字符串名称;

公共列表< WorkLog> getWorklogs(){
返回工作日志;
}

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实现了JsonSerializer< Book>,JsonDeserializer< Book> 
{
Gson gson = new Gson();

public JsonElement serialize(Book book,type typeOfT,JsonSerializationContext context)
{
JsonObject json = new JsonObject(); (用户用户:book.getUser())
{
json.addProperty(user.getName(),gson.toJson(user));


}

返回json;
}

public Book deserialize(JsonElement element,type typeOfT,JsonDeserializationContext context)throws JsonParseException
{
JsonObject json = element.getAsJsonObject();

Book book = new Book(); (Entry< String,JsonElement>条目:json.entrySet())

(b
String name = entry.getKey();
User user = gson.fromJson(entry.getValue(),User.class);
user.setName(name);

book.getUser()。add(user);
}

归还书;


$ / code>

和往返:

  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\:\\\\
cccccc\,+
\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);

字符串json = gson.toJson(book);

查看我的教程,了解Gson的可能性: <与Gson的Java / JSON映射



享受! :)

I have a JSON object like this:

{
  "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 = new Gson();
Book responseBean = gson.fromJson(jsonString, Book.class);

But the 'responceBean' is always '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.

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! :)

这篇关于使用GSON解析JSON对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆