如何使用Java中的GSON解析来自Web服务响应的复杂JSON String?

时间:2012-01-17 00:35:41

标签: json gson

大家好,

      I am new to Json/Gson. I have already looked all around the internet for help, but I     have seen nothing so similar to what I need to parse. So I am posting here, any help will be appreciated.  

我收到来自webservice的回复我称之为Json String:

        Json String = {"courses":[{"links":         [{"href":"https://xp.student.com/courses/6364145","rel":"self","title":"course"}]},         {"links":    [{"href":"https://xp.student.com/courses/6364143","rel":"self","title":"course"}]},
        {"links":    [{"href":"https://xp.student.com/courses/6364144","rel":"self","title":"course"}]}]}  

我已经完成了代码,直到我得到“Json String”:

    InputStreamReader reader = new InputStreamReader(httpConn.getInputStream());
        in = new BufferedReader(reader);
     Gson gson = new Gson();
     Course courses = new Gson().fromJson(in,Course.class);

我还创建了以下类:

        import ccSample.Type.Course.Link;

        public class Course {

        public Link links[];

        } 

        public class Link{
        public String href;
        public String rel;
        public String title;
        public String getHref() {
        return href;
        }
       public void setHref(String href) {
       this.href = href;
        }
        public String getRel() {
        return rel;
        }
        public void setRel(String rel) {
        this.rel = rel;
        }
        public String getTitle() {
        return title;
        }
        public void setTitle(String title) {
        this.title = title;
        }

        }





         but I am just getting a null courses object and do not know what I am missing,     any suggestions corrections are welcome!

    Thank you very much :)

2 个答案:

答案 0 :(得分:0)

这是一层洋葱。一次剥一个。您可以使用instanceof运算符和/或getClass().getName()方法调用来确定每个步骤中的内容,并按预期进行仔细检查。

答案 1 :(得分:0)

啊,好吗......

你需要另一个课程包装器,因为在回复中它包含在另一个json对象

    public class Reply {
    private Course[] courses;

    public void setCourses(Course[] courses) {
        this.courses = courses;
    }

    public Course[] getCourses() {
        return courses;
    }
}

然后

Reply reply = new Gson().fromJson(in,Reply.class);

应该这样做:)