2

嗨,我有一个 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"}]}

及其域为 This

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映射到对象,如下所示

仅供参考:对于 jsonString,我传递的是字符串而不是 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/生成的类定义是正确的

知道它在哪里做错了吗?

4

2 回答 2

2

jsonString包含分配给 的一个arraylist多个对象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;
    }
}

和这个:

Lines ln = new Gson().fromJson(jsonString, Lines.class);
于 2012-09-05T09:17:33.253 回答
1

你的 json 没有直接返回Line class.它正在返回Lines class. ,你正在尝试cast it into Linewhich 不是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.

于 2012-09-05T06:45:38.897 回答