java 如何将 JSON 对象从 Gson 转换为 POJO
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31073624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert JSON objects to POJO from Gson
提问by ricardoramos
I am trying to convert JSON objects to POJO's with GSON.
我正在尝试使用 GSON 将 JSON 对象转换为 POJO。
JSON String
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
}
}
]
The AutomationProjectsList class used with GSON
与 GSON 一起使用的 AutomationProjectsList 类
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
+ "]";
}}
Automation Project POJO
自动化项目 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;
}}
The code I'm using
我正在使用的代码
JSONArray jsonArray = new 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)
Why am I receiving an IndexOutOfBoundsException exception? Where am I wrong?
为什么我会收到 IndexOutOfBoundsException 异常?我哪里错了?
采纳答案by Onheiron
Your class or your JSON are incorrect. I'd suggest your JSON is. A JSON matching your POJO class would be:
您的课程或您的 JSON 不正确。我建议你的 JSON 是。与您的 POJO 类匹配的 JSON 将是:
{
"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
}
]
}
Notice I used the name automationProjects for the list as it makes more sense, so your class would be:
请注意,我在列表中使用了名称automationProjects,因为它更有意义,因此您的类将是:
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
+ "]";
}
}
And finally to convert JSON to AutomationProjectsList object:
最后将 JSON 转换为 AutomationProjectsList 对象:
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:
总之,您的代码似乎存在以下问题:
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?If you model your class correctly on the JSON then you don't need to iterate the JSON to obtain your objects
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?
你有一个列表列表还是只有一个项目列表?如果列表只是一个,为什么要
jsonArray
像它的子对象本身就是列表一样进行迭代?如果您在 JSON 上正确建模您的类,那么您不需要迭代 JSON 来获取您的对象
您发布的 JSON 非常奇怪,并且难以与 Gson 一起使用,这是一项要求还是您可以随意编辑它?
Hope this helps
希望这可以帮助
EDIT
编辑
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:
既然你说你不能改变你得到的 JSON,那么它会变得更复杂一些,但一切都取决于对 JSON 格式的类进行建模。所以让我们从这个 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
}
}
]
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.
现在,这很糟糕,但让我们看看这里有什么:我们有一个未命名的对象数组,其中有一个属性"automationProject"
,即我们实际的 AutomationProject 对象。因此,就结构而言,它是一个包含实际自动化项目的对象列表。
Thus you'll need to get rid of your AutomationProjectList and change it with the more meaningful AutomationProjectWrapper looking as fallows:
因此,您需要删除您的 AutomationProjectList 并使用更有意义的 AutomationProjectWrapper 进行更改,看起来像休耕:
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
+ "]";
}
}
See this class is equivalent to the JSON Object:
看这个类相当于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
}
}
Finally you'll have an array of such wrapper objects as your jsonArray so you can write:
最后,您将拥有一个此类包装器对象的数组作为 jsonArray,因此您可以编写:
AutomationProjectWrapper[] projectsList = new Gson().fromJson(jsonArray.toString(), AutomationProjectWrapper[].class);
Then to log your objects:
然后记录您的对象:
for(AutomationProjectWrapper wrapper : projectsList){
System.out.println(wrapper.getAutomationProject().getId());
}
EDIT 2
编辑 2
Sorry for the mistake, in AutomationProjectWrapper
class the AutomationProject
field should be named automation_project
.
Fixed in code above.
对不起,在AutomationProjectWrapper
课堂上,该AutomationProject
字段应命名为automation_project
。在上面的代码中修复。
回答by Panagiotis Stoupos
According to your JSON String the value you are trying to access is :
根据您的 JSON 字符串,您尝试访问的值是:
jsonString[i].automation_project.user_id
In your code you have: obj.getAutomationProject().get(0).getId()
在您的代码中,您有: obj.getAutomationProject().get(0).getId()
I think is should be: obj[i].getAutomationProject().getId()
我认为应该是: obj[i].getAutomationProject().getId()