Gson - Json列表到Java List <object> </object>

时间:2014-08-28 19:51:23

标签: java json gson

我在将Json对象列表转换为Java List时遇到了一些问题。我正在使用GSon来做到这一点。 我有以下Json列表:

{"player":
    [
    {"id":"1","age":"25","name":"Neuer"},
    {"id":"2","age":"26","name":"Cristiano Ronaldo"},
    {"id":"3","age":"24","name":"Lionel Messi"}
    ]
}

我有以下Java对象:

public class PlayerDTO implements Serializable {

    private int id;
    private String name;
    private int age;

    //Getters and Setters
}

在我的Java课程中我正在做:

Type collectionType = new TypeToken<ArrayList<PlayerDTO>>(){}.getType();
List<PlayerDTO> players = gson.fromJson(jsonString, collectionType);

但是,当Gson尝试转换Json列表时,我收到错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
at com.google.gson.Gson.fromJson(Gson.java:817)
at com.google.gson.Gson.fromJson(Gson.java:770)
at com.google.gson.Gson.fromJson(Gson.java:719)
at com.google.gson.Gson.fromJson(Gson.java:691)
at br.com.test.TesteGson.main(TesteGson.java:33)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:351)
at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:70)
at com.google.gson.Gson.fromJson(Gson.java:805)
... 4 more

据我所知,这是因为Gson期待Json在Json String的开头没有 “player” 。你能帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

解决此问题的最简单方法是创建一个Players类作为玩家的集合。

以下是Players类:

import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;

public class Players {

@Expose
private List<Player> players = new ArrayList<Player>();

public List<Player> getPlayer() {
return player;
}

public void setPlayer(List<Player> player) {
this.player = player;
}

}

Player类:

import com.google.gson.annotations.Expose;

public class Player {

@Expose
private String id;
@Expose
private String age;
@Expose
private String name;

public String getId() {
return id;
}

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

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}

public String getName() {
return name;
}

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

}