1

我有来自 url 的以下 json 响应:

stdClass Object
(
    [uname] => Eamorr
    [phoneNumber] => 082732938293
    [fname] => Steve
    [lname] => Hearst
    [sex] => M
    [roofSignNumber] => 230948
    [vehicleReg] => 07D2892
    [vehicleMake] => Toyota
    [vehicleModel] => Avensis
    [vehicleNumPassengers] => 4
    [profilePic] => -1
    [online] => 1
    [status] => 
    [picList] => Array
        (
        )

    [lat] => 
    [lng] => 
    [reputation] => 0.63
    [numPagesComments] => 1
    [last5comments] => Array
        (
            [0] => stdClass Object
                (
                    [comment] => hello5
                    [fromUname] => Eamorr
                    [profilePic] => -1
                    [time] => 1290254763
                    [id] => 23628mr28018onm647z2
                )

        )

)

这就是我进行解析的方式:

                      Gson json=new Gson();
                      try{
                          Driver driver=json.fromJson(response,Driver.class);
                          Log.i("json",driver.profilePic);
                      }catch(JsonParseException e){
                          Log.i("error","JsonParseException");
                      }

运行代码时,出现此错误: ERROR/AndroidRuntime(823): java.lang.RuntimeException: No-args constructor for class com.project.driver.Driver$Post 不存在。使用 Gson 为该类型注册一个 InstanceCreator 以解决此问题。

我在为解析定义合适的 Driver.java 时遇到了麻烦。当我省略“last5comments”字段时,一切正常,只是“last5comments”位我遇到了麻烦......

这是Driver.java:

public class Driver {
    public String uname="";
    public String phoneNumber="";
    public String fname="";
    public String lname="";
    public String sex="";
    public String roofSignNumber="";
    public String vehicleReg="";
    public String vehicleMake="";
    public String vehicleModel="";
    public String vehicleNumPassengers="";
    public String profilePic="";
    public String online="";
    public String status="";
    public String[] picList;
    public String lat="";
    public String lng="";
    public String reputation="";
    public String numPagesComments="";

    //having problems below this line 
    public Post[] last5comments;

    public class Post{
        public String comment="";
        public String fromUname="";
        public String profilePic="";
        public String time="";
        public String id="";
    }
}

非常感谢任何有关定义合适 Driver.java 的帮助。

提前致谢,

4

1 回答 1

7

我通过查看以下内容设法解决了这个问题:

http://sites.google.com/site/gson/gson-user-guide#TOC-Nested-Classes-including-Inner-Clas

(关于“嵌套类(包括内部类)”的部分)

我所要做的就是将 Post 对象设为静态。

public static class Post{
        public String comment="";
        public String fromUname="";
        public String profilePic="";
        public String time="";
        public String id="";
    }
于 2010-11-24T13:08:00.683 回答