我有json字符串,我想从该字符串中获取数据..
jsonString 数据就像
[{"Eid":"1","name":"Rahim"},{"Eid":"2","name":"Karim"}]
我试过下面的代码
员工类
public class Employee {
private String Eid;
private String name;
//setters and getters
Employee(){};//constructor
Employee(String Eid,String name){}//constructor
}
主要课程
try{
JSONArray jsonarray = new JSONArray(jsonString);
Gson gson = new Gson();
Employee employee = new Employee();
employee= gson.fromJson(jsonarray.toString(), Employee.class);
//display every employee details
logger.info(employee);
}
catch (Exception e) {
logger.error("Employee save > Error: " + e.getMessage());
}
但是得到错误:
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
答案 0 :(得分:1)
请尝试以下代码:
Employee[] employeeArray= gson.fromJson(jsonarray.toString(), Employee[].class);
// iterate on employeeArray
for(Employee employee :employeeArray){
// here you can do your task on employee object
}
答案 1 :(得分:0)
您正在阅读员工记录集而不是单个员工集。所以你应该使用ArrayList或任何List类
修改下面的代码(我已经测试过相同的工作正常)
try{
//we dont need json array .. just use the json string
Gson gson = new Gson();
Employee employee = new Employee();
List<Employee> employeeList = gson.fromJson(jsonString, ArrayList.class);
//display every employee list details
logger.info("employeeList : " + employeeList.size());
}
[output] employeeList : 2
演示: Test.java
public class Test {
public static void main(String[] args) {
try {
String json = "[{\"Eid\":\"1\",\"name\":\"Rahim\"},{\"Eid\":\"2\",\"name\":\"Karim\"}]";
System.out.println(json);
Gson gson = new Gson();
List<Employee> employeeList = gson.fromJson(json, ArrayList.class);
System.out.println(employeeList.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Employee.java
public class Employee implements java.io.Serializable {
private String Eid;
private String name;
public String getEid() {
return Eid;
}
public void setEid(String eid) {
Eid = eid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
gson.fromJson(json, ArrayList.class);
此行将从JSON准备一份员工对象列表,并在将列表分配给Employee类型[List<Employee> employeeList=gson.fromJson(json, ArrayList.class);
]时,它会将对象类型转换为员工类类型。