我正在尝试解析除了对象之外没有任何键的JSON。
例如:
[
{
"OBJECT1":{
....
}
},
"OBJECT2":{
....
}
}
]
在这种情况下,我试图像List对象一样解析这个JSON,而Object类包含这些对象内的值。我不知道我做得对不对。
Gson的错误响应是
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
我正在正确解析JSON ??
答案 0 :(得分:1)
您可以使用Gson library。如果我们假设你的对象是像这样的人类
class Person{
String name;
int age;
}
和你的json响应一样
[
{
"OBJECT1":{
"name":"mohamed",
"age":21
},
"OBJECT2":{
"name":"shalan",
"age":21
}
}
]
您需要创建一个类来反映json中的每个对象 for Object1
public class OBJECT1 {
@SerializedName("name")
@Expose
private String name;
@SerializedName("age")
@Expose
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
和你的Object2
public class OBJECT2 {
@SerializedName("name")
@Expose
private String name;
@SerializedName("age")
@Expose
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
这是一个用于保存对象的人员类
public class Person {
@SerializedName("OBJECT1")
@Expose
private OBJECT1 oBJECT1;
@SerializedName("OBJECT2")
@Expose
private OBJECT2 oBJECT2;
public OBJECT1 getOBJECT1() {
return oBJECT1;
}
public void setOBJECT1(OBJECT1 oBJECT1) {
this.oBJECT1 = oBJECT1;
}
public OBJECT2 getOBJECT2() {
return oBJECT2;
}
public void setOBJECT2(OBJECT2 oBJECT2) {
this.oBJECT2 = oBJECT2;
}
}
将您的json数组转换为对象列表
Gson gson = new Gson();
String jsonOutput = "your json result is here";
Type listType = new TypeToken<List<Person>>(){}.getType();
List<Persopn> persons = (List<Person>) gson.fromJson(jsonOutput, listType);
答案 1 :(得分:-1)
看起来像语法错误,试试这个: -
[
{
"OBJECT1":[ {le:"Dashobard",level:"01"},{name:"About Us",level:"02"},{name:"Contact Us",level:"03"},{name:"Dashobard",level:"04"}
]
},
{ "OBJECT2":[ {le:"Dashobard",level:"01"},{name:"About Us",level:"02"},{name:"Contact Us",level:"03"},{name:"Dashobard",level:"04"}
]
}
]