使用GSON进行JSON反序列化

时间:2010-11-24 12:04:25

标签: android json parsing gson

我从网址获得以下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:类com.project.driver.Driver的No-args构造函数$ 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的帮助。

提前致谢,

1 个答案:

答案 0 :(得分: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="";
    }