通过Gson强制转换异常

时间:2017-11-18 08:14:11

标签: android gson

我有这种json形式:

[
{
    "command":"",
    "name":"گزارش صدور",
    "children":
    [
        {
            "command":"ReportDaily",
            "name":"Daily",
            "children":[],
            "path":"/Sa/Certificates_Daily",
            "params":
            {
                "PeriodType":"1",
                "District":"0"
            }
        },
        {
            "command":"ReportWeekly",
            "name":"Weekly",
            "children":[],
            "path":"/Sa/Certificates_Daily",
            "params":
            {
                "PeriodType":"2",
                "District":"0"
            }
        }
    ],
    "path":"",
    "params":{}
},...

现在我想将它转换为java对象,因为我创建了这个pojo类:

public class HierarchicalResource {
public String command;
public String name;
public List<HierarchicalResource> children;
public String path;
public Params params;


public class Params {
    public String PeriodType;
    public String District;
}
}

通过 Gson()我把这个json变成这样的java对象:

 return new Gson().fromJson(sb.toString(),new TypeToken<HierarchicalResource[]>(){}.getType());

但是我收到了这个错误:

java.lang.ClassCastException: com.views.HierarchicalResource[] cannot be cast to com.views.HierarchicalResource

为什么它不能将我的类转换为HierarchicalResource?

1 个答案:

答案 0 :(得分:2)

似乎您的方法被声明为返回com.views.HierarchicalResource,但您返回的是数组com.views.HierarchicalResource[]

将方法返回类型更改为com.views.HierarchicalResource[]