如何用Java中的GSON解析从webservice响应获得的复杂JSON字符串?
大家好,如何用Java中的GSON解析从webservice响应获得的复杂JSON字符串?,json,gson,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. 我从我调用此Json字符串的Web服务接收到响应: Json St
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"}]}]}
InputStreamReader reader = new InputStreamReader(httpConn.getInputStream());
in = new BufferedReader(reader);
Gson gson = new Gson();
Course courses = new Gson().fromJson(in,Course.class);
我已经编写了代码,直到得到“Json字符串”:
我还创建了以下类:
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 :)
这是一层层洋葱。一次剥一个。您可以使用
instanceof
运算符和/或getClass().getName()
方法调用来计算每个步骤中的内容,并仔细检查是否符合预期。啊,明白了
您需要另一个课程包装器,因为在回复中,它包含在另一个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(在Reply.class中)代码>
应该这样做:)