2012-01-17 67 views
0

大家好,如何解析一個複雜的JSON字符串從Web服務響應中獲取與Java中的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. 

我收到了來自我打電話這個JSON字符串的Web服務的響應:

 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字符串「:

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 :) 

回答

0

它是一層洋蔥。一次剝一個。您可以使用instanceof運算符和/或getClass().getName()方法調用來確定每個步驟中的含義,然後仔細檢查它是否符合預期。

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);

應該做的它:)

相關問題