如何将JSON对象从Gson转换为POJO [英] How to convert JSON objects to POJO from Gson

查看:101
本文介绍了如何将JSON对象从Gson转换为POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用GSON将JSON对象转换为POJO.

I am trying to convert JSON objects to POJO's with GSON.

JSON字符串

[
  {
    "automation_project": {
      "user_id": null,
      "name": "Untitled Project",
      "updated_at": "2015-06-16T19:39:42Z",
      "group_id": 764496,
      "created_at": "2014-11-23T01:01:59Z",
      "id": 16214
    }
  },
  {
    "automation_project": {
      "user_id": null,
      "name": "newintropage",
      "updated_at": "2015-06-16T21:20:47Z",
      "group_id": 764496,
      "created_at": "2015-06-16T20:39:04Z",
      "id": 29501
    }
  }
]

与GSON一起使用的AutomationProjectsList类

The AutomationProjectsList class used with GSON

public class AutomationProjectsList {

private List<AutomationProject> automationProject = new ArrayList<AutomationProject>();

public List<AutomationProject> getAutomationProject() {
    return automationProject;
}

public void setAutomationProject(List<AutomationProject> automationProject) {
    this.automationProject = automationProject;
}

@Override
public String toString() {
    return "AutomationProjectsList [automationProject=" + automationProject
            + "]";
}}

自动化项目POJO

 public class AutomationProject {

    private Object userId;   
    private Integer groupId;    
    private Integer id;    
    private String name;   
    private String updatedAt;   
    private String createdAt;

    public Object getUserId() {
        return userId;
    }

    public void setUserId(Object userId) {
        this.userId = userId;
    }

    public Integer getGroupId() {
        return groupId;
    }

    public void setGroupId(Integer groupId) {
        this.groupId = groupId;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }}

我正在使用的代码

JSONArray jsonArray =新的JSONArray(response.getEntity(String.class));

JSONArray jsonArray = new JSONArray(response.getEntity(String.class));

    for(int i = 0; i < jsonArray.length(); i++){
        if(jsonArray.get(i) instanceof JSONObject){
            JSONObject jsnObj = (JSONObject)jsonArray.get(i);               
            AutomationProjectsList obj = new Gson().fromJson(jsnObj.toString(), AutomationProjectsList.class);                  
            System.out.println(obj.getAutomationProject().get(0).getId());
        }
    }

但是它给出了一个例外:

But it gives an exception :

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at br.usp.icmc.teste.ConnectionRestClient.getBrowserStackProjects(ConnectionRestClient.java:74)
at br.usp.icmc.teste.TestePrincipal.main(TestePrincipal.java:9)

为什么会收到IndexOutOfBoundsException异常?我在哪里错了?

Why am I receiving an IndexOutOfBoundsException exception? Where am I wrong?

推荐答案

您的类或JSON不正确.我建议您使用JSON. 与POJO类匹配的JSON为:

Your class or your JSON are incorrect. I'd suggest your JSON is. A JSON matching your POJO class would be:

{
  "automationProjects":[
    {
      "user_id": null,
      "name": "Untitled Project",
      "updated_at": "2015-06-16T19:39:42Z",
      "group_id": 764496,
      "created_at": "2014-11-23T01:01:59Z",
      "id": 16214
    },
    {
      "user_id": null,
      "name": "newintropage",
      "updated_at": "2015-06-16T21:20:47Z",
      "group_id": 764496,
      "created_at": "2015-06-16T20:39:04Z",
      "id": 29501
    }
  ]
}

注意,我在列表中使用了名字AutomationProjects,因为它更有意义,所以您的课程将是:

Notice I used the name automationProjects for the list as it makes more sense, so your class would be:

public class AutomationProjectsList {

    private List<AutomationProject> automationProjects = new ArrayList<AutomationProject>();

    public List<AutomationProject> getAutomationProjects() {
        return automationProjects;
    }

    public void setAutomationProjects(List<AutomationProject> automationProjects) {
        this.automationProjects = automationProjects;
    }

    @Override
    public String toString() {
        return "AutomationProjectsList [automationProject=" + automationProject
        + "]";
    }
}

最后将JSON转换为AutomationProjectsList对象:

And finally to convert JSON to AutomationProjectsList object:

AutomationProjectsList projectsList = new Gson().fromJson(jsonArray.toString(), AutomationProjectsList.class);

然后,如果您想记录每个项目:

Then if you want to log each project:

for(AutomationProject project : projectsList.automationProjects){
  System.out.println(porject.getId());
}

总而言之,您的代码似乎存在以下问题:

In conclusion, your code seems to have the fallowing issues:

  1. 您有列表列表还是仅一个项目列表?如果列表只是一个,为什么要像jsonArray那样将其子对象作为列表本身进行迭代?

  1. Do you have a list of lists or just a single list of projects? If the list is just one, why do you iterate jsonArray like its sub-objects are lists themselves?

如果您在JSON上正确地对类进行建模,则无需迭代JSON即可获取对象

If you model your class correctly on the JSON then you don't need to iterate the JSON to obtain your objects

您发布的JSON非常奇怪且不易与Gson一起使用,是一项要求还是可以根据需要对其进行编辑?

The JSON you posted is quite weird and uneasy to use with Gson, is it a requirement or can you edit it as you please?

希望这会有所帮助

由于您声明无法更改所获取的JSON,因此它变得稍微复杂一点,但是一切都取决于使用JSON格式对类进行建模.因此,让我们开始使用此JSON:

Since you stated you cannot change the JSON you get, then it gets a little more complex, but everything is up to modelling the classes on the JSON format. So let's start form this JSON:

[
    {
        "automation_project": {
            "user_id": null,
            "name": "Untitled Project",
            "updated_at": "2015-06-16T19:39:42Z",
            "group_id": 764496,
            "created_at": "2014-11-23T01:01:59Z",
            "id": 16214
        }
    },
    {
        "automation_project": {
            "user_id": null,
            "name": "newintropage",
            "updated_at": "2015-06-16T21:20:47Z",
            "group_id": 764496,
            "created_at": "2015-06-16T20:39:04Z",
            "id": 29501
        }
    }
]

现在,这很讨厌,但是让我们看看这里有什么:我们有一个具有单个属性"automationProject"的未命名对象数组,这是我们实际的AutomationProject对象.因此,就结构而言,它是包装实际的AutomationProject的对象列表.

Now, this is quite nasty, but let's see what we have here: we have an unnamed array of objects with a single attribute "automationProject" which is our actual AutomationProject Object. So in terms of structure, it is a list of objects which wrap an actual AutomationProject.

因此,您将需要删除AutomationProjectList并使用更有意义的AutomationProjectWrapper对其进行更改:

Thus you'll need to get rid of your AutomationProjectList and change it with the more meaningful AutomationProjectWrapper looking as fallows:

public class AutomationProjectsWrapper {

    private AutomationProject automation_project = new AutomationProject();

    public AutomationProject getAutomationProject() {
        return automation_project;
    }

    public void setAutomationProject(AutomationProject automationProject) {
        this.automation_project = automationProject;
    }

    @Override
    public String toString() {
        return "AutomationProjectsList [automationProject=" + automation_project
        + "]";
    }
}

请参阅此类等同于JSON对象:

See this class is equivalent to the JSON Object:

{
    "automation_project": {
        "user_id": null,
        "name": "Untitled Project",
        "updated_at": "2015-06-16T19:39:42Z",
        "group_id": 764496,
        "created_at": "2014-11-23T01:01:59Z",
        "id": 16214
    }
}

最后,您将拥有jsonArray这样的包装对象数组,因此您可以编写:

Finally you'll have an array of such wrapper objects as your jsonArray so you can write:

AutomationProjectWrapper[] projectsList = new Gson().fromJson(jsonArray.toString(), AutomationProjectWrapper[].class);

然后记录您的对象:

for(AutomationProjectWrapper wrapper : projectsList){
    System.out.println(wrapper.getAutomationProject().getId());
}

编辑2

很抱歉,在AutomationProjectWrapper类中,AutomationProject字段应命名为automation_project. 已在上面的代码中修复.

EDIT 2

Sorry for the mistake, in AutomationProjectWrapper class the AutomationProject field should be named automation_project. Fixed in code above.

这篇关于如何将JSON对象从Gson转换为POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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