The error is saying
Expected BEGIN_ARRAY...
because of the second argument (Agent[].class
), it is expecting a valid json array string of Agent
-s.
Your json string is an object with a key Agents
and the value is an array of Agent
s.
A possible solution could be for example creating a class named Agents
which represents the json object.
public class Agents {
private Agent[] Agents; // note the capital 'A' matches the key name in the json string
public Agent[] getAgents() {
return Agents;
}
public void setAgents(Agent[] agents) {
this.Agents = agents;
}
}
And adjust the Agent class as follows:
public class Agent {
@SerializedName("Id") // note the annotated field is needed since in the json string id is Id
private int id;
@SerializedName("Owner") // same as id field, annotation needed, or rename owner to Owner
private String owner;
public Agent(int id, String owner) {
this.id = id;
this.owner = owner;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public void setOwner(String owner) {
this.owner = owner;
}
@Override
public String toString() {
return "Agent{" +
"id=" + id +
", owner='" + owner + ''' +
'}';
}
}
And here's a working demo:
public class GsonDemo {
public static void main(String[] args) {
String json = "{"Agents":[{"Id":"1","Owner":"Andre"},{"Id":"7","Owner":"Andre2"},{"Id":"8","Owner":"Andre"},{"Id":"9","Owner":"Alexander"},{"Id":"10","Owner":"Alexander"},{"Id":"12","Owner":"Andre"}]}";
Gson gson = new Gson();
Agents a = gson.fromJson(json, Agents.class);
System.out.println(a.getAgents()[1]);
System.out.println(a.getAgents().length);
// Output:
// Agent{id=7, owner='Andre2'}
// 6
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…