Gson无法解析数组。但它是json数组

时间:2014-04-13 10:59:50

标签: android json gson

我有以下json字符串:

{"objKampfEntry":[{"deffSpielerId":"9","kampfId":"7","offSpielerId":"10","rundeCounter":"0","rundenList":[{"deffIsReady":"0","deffMove":"0","deffSpieler":{"ausdauer":"5","eiId":"0","gesichtId":"normal","helm":"0","id":"13","kraft":"6","leben":"12","lebenMax":"50","level":"1","name":"Test","niederlagen":"0","punkte":"1","rang":"1","rustung":"0","siege":"0","timestamp":"1397385595686","waffe":"0"},"done":"0","kampfId":"7","offIsReady":"1","offMove":"0","offSpieler":{"ausdauer":"5","eiId":"0","gesichtId":"normal","helm":"0","id":"14","kraft":"6","leben":"12","lebenMax":"50","level":"1","name":"Test2","niederlagen":"0","punkte":"1","rang":"1","rustung":"0","siege":"0","timestamp":"1397385841118","waffe":"0"},"rundeNr":"0","winner":"0"}]}]}

如果我使用

Gson gson = new Gson();
Type listOfKampfEntry = new TypeToken<List<ObjKampfEntry>>(){}.getType();
ArrayList<ObjKampfEntry> list = gson.fromJson(json, listOfKampfEntry);

我收到此错误:

04-13 12:45:48.706: W/System.err(4411): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
04-13 12:45:48.706: W/System.err(4411):     at com.google.gson.Gson.fromJson(Gson.java:815)
04-13 12:45:48.706: W/System.err(4411):     at com.google.gson.Gson.fromJson(Gson.java:768)
04-13 12:45:48.706: W/System.err(4411):     at com.google.gson.Gson.fromJson(Gson.java:717)

所以我有一个objKampfEntry数组并且在rundenList数组中。我做错了什么?

我的ObjKampfEntry类:

public class ObjKampfEntry {

    private long kampfId;
    private long offSpielerId;
    private long deffSpielerId;

    private int rundeCounter;

    private ArrayList<Runde> rundenList = new ArrayList<Runde>();
    //constructor and getter/setter

}

和runde对象

public class Runde {

    private long kampfId;
    private long winner;
    private int rundeNr;
    private int offIsReady;
    private int deffIsReady;
    private int done;
    private Spieler offSpieler;
    private Spieler deffSpieler;
    private int offMove;
    private int deffMove;
...

这里是Spieler对象

public abstract class ACharakter {

    protected long id;
    protected String name;
    protected int leben;
    protected int lebenMax;
    protected int kraft;
    protected int ausdauer;

public class Spieler extends ACharakter {

    private int rang;
    private int level;
    private int punkte;
    private long timestamp;
    private int waffe;
    private int rustung;
    private int helm;
    private int siege;
    private int niederlagen;
    private int eiId;
    private String gesichtId;

1 个答案:

答案 0 :(得分:3)

您输入的不是 ObjKampfEntry个对象的JSON数组。相反,它是一个带有一个键/值对的JSON 对象,其值是ObjKampfEntry个对象的JSON数组。

&#34;正确&#34;根据您的方案输入的内容为[{"deffSpielerId":"9","kampfId":"7",...}],因为它确实会映射到List<ObjKampfEntry>。如果您无法更改输入,则您需要另一个类,其中包含一个名为objKampfEntry的{​​{1}}类型的字段:

List<ObjKampfEntry>