Android gson无效ClassCastException

时间:2012-09-05 06:20:29

标签: java android gson

您好我有一个Json字符串

   {"lines":[{"line":"COLOMBO - BADULLA"},{"line":"COLOMBO - MATALE"},{"line":"COLOMBO - PUTTLAM"},{"line":"COLOMBO - THANDIKULAM"},{"line":"COLOMBO - TALAIMANNAR"},{"line":"COLOMBO - BATTICALOA"},{"line":"COLOMBO - TRINCOMALEE"},{"line":"COLOMBO - MATARA"},{"line":"COLOMBO - AVISSAWELLA"},{"line":"COLOMBO - MIHINTALE"}]}

其域为此

public class Line{
    private String line;

    public String getLine(){
        return this.line;
    }
    public void setLine(String line){
        this.line = line;
    }
}



public class Lines{
    private List lines;

    public List getLines(){
        return this.lines;
    }
    public void setLines(List lines){
        this.lines = lines;
    }
}

gson映射到对象作为此

FYI:对于jsonString,我传递String而不是JSON URL (使用HttpGet)

    Line ln =null;
    Gson gson = new Gson();
    ln = gson.fromJson(jsonString, Line.class); not the URL
    return ln;

抛出的异常是:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sab.loc/com.sab.loc.MainActivity}: java.lang.ClassCastException: com.sab.loc.Line cannot be cast to java.util.List

我不确定会出现什么问题,我认为我的班级定义是正确的,我使用http://jsongen.byingtondesign.com/

生成

知道哪里出错了?

2 个答案:

答案 0 :(得分:2)

您的jsonString包含分配给array的{​​{1}}或list个对象。

lines

因此,您尝试将此{"lines":[{"line":"COLOMBO - BADULLA"},...]}数据映射到的类必须具有jsonString变量。

lines类没有Line.java变量。

试试这个:

lines

而且:

public class Lines {
    private List<Line> lines;

    public List<Line> getLines(){
        return this.lines;
    }
    public void setLines(List<Line> lines){
        this.lines = lines;
    }
}

public class Line {
    private String line;

    public String getLine(){
        return this.line;
    }
    public void setLine(String line){
        this.line = line;
    }
}

答案 1 :(得分:1)

您的json没有直接返回Line class.它正在返回Lines class. 并且你正试图cast it into Line List这不是throwing class cast exception那种方式 它是private List lines;

您可以在Line.java class内定义字段generic type private List<Lines> lines;

最好在Line.java课程中定义generate the setter getter stubs of lines 和{{1}}。