调用接口返回的数据,解析json并以对象的形式存到数据库

public class Test1 {
public static void main(String[] args) {
String content = “{“openId”:1,“answers”:[{“questionId”:1,“selectName”:“A”},{“questionId”:2,“selectName”:“B”},{“questionId”:3,“selectName”:“D”},{“questionId”:4,“selectName”:“AC”}]}”;
JSONObject responseJson = JSONObject.fromObject(content);
Object openId = responseJson.get(“openId”);
JSONArray answers = JSONArray.fromObject(responseJson.get(“answers”) + “”);
Answer my = null;
for (int i = 0; i < answers.size(); i++) {
JSONObject answer = JSONObject.fromObject(answers.get(i));
my = (Answer) JSONObject.toBean(answer, Answer.class);
my.setOpenId(openId.toString());
System.out.println(my.toString());
}
}
}

打印的结果是:
Answer [openId=1, questionId=1, selectName=A]
Answer [openId=1, questionId=2, selectName=B]
Answer [openId=1, questionId=3, selectName=D]
Answer [openId=1, questionId=4, selectName=AC]

然后你可以取出来存到数据库

public class Answer {
String openId;
String questionId;
String selectName;

public String getOpenId() {
    return openId;
}
public void setOpenId(String openId) {
    this.openId = openId;
}
public String getQuestionId() {
    return questionId;
}
public void setQuestionId(String questionId) {
    this.questionId = questionId;
}
public String getSelectName() {
    return selectName;
}
public void setSelectName(String selectName) {
    this.selectName = selectName;
}
@Override
public String toString() {
    return "Answer [openId=" + openId + ", questionId=" + questionId + ", selectName=" + selectName + "]";
}

}

猜你喜欢

转载自blog.csdn.net/qq_30347133/article/details/88691270