请问各位大神这个要怎么处理 而且存入数据库的时候 是一次性存入问题1 2 3 和他对应的答案 多条数据 每个题还得带上用户的id(就是前面的openId) 都是一样的
解析看这个例子
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
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]
然后你可以取出来存到数据库
sql语句的insert是可以支持一次性多条插入的 格式
insert into table(filed1,filed2.....) values(值1,值1,....),(值2,值2..)....
你可以将这条json遍历一遍取出每个字断的值,拼去sql中 然后去执行这条sql
最好把json中的数据取出来,设置到bean的各个属性中去,然后再存到数据库。
忘了这个
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 + "]";
}
}
js中可以直接用eval把json字符串转为js对象,然后通过点属性的方式取到数据。数据部分就是obj.answers是一个数组,直接把数组传到后台就可以了。
或者直接转为map,,getkey不就拿到数据了么。传到后台处理就完了。
http://cloudyxuq.iteye.com/blog/1618213
直接把整个字符串传到后台也是可以的。就像你写那样,直接转为Bean。前提是你要先定义一个和JSON结构类似的 bean.
http://blog.csdn.net/tsyj810883979/article/details/8633786
你自己写个例子试下就知道了。真心不难,超简单。别人不可能帮你把代码全都写出来。
楼上左边的方式就可以。解决的办法挺多的,随便选一种就行。