JSON的String字符串与Java的List列表对象的相互转换
在前端:
1.如果json是List对象转换的,可以直接遍历json,读取数据。
2.如果是需要把前端的List对象转换为json传到后台,param是ajax的参数,那么转换如下所示:
varjsonStr=JSON.stringify(list);
varparam={};
param.jsonStr=jsonStr;
在后台:
1.把String转换为List(str转换为list)
List<T>list=newArrayList<T>(); JSONArrayjsonArray=JSONArray.fromObject(str);//把String转换为json list=JSONArray.toList(jsonArray,t);//这里的t是Class<T>
2.把List转换为json
JSONArrayjson=JSONArray.fromObject(object); Stringstr=json.toString();//把json转换为String
eg:
1. 根据页面用户输入的信息形成Answer对象的List
/**
*@paramanswers
*@paramquestion_ids
*@paramtypes
*@return
*/
privateList<Answer>toAnswerList(String[]studenAnswers,int[]question_ids,
int[]types,int[]scores){
List<Answer>answerList=newArrayList<Answer>();
if(studenAnswers!=null&&question_ids!=null&&types!=null&&scores!=null){
for(inti=0;i<studenAnswers.length;i++){
Answeranswer=newAnswer();
StringstudenAnswer=studenAnswers[i];
inttype=types[i];
intquestion_id=question_ids[i];
intscore=scores[i];
answer.setQuestion_id(question_id);
answer.setScore(score);
answer.setStudenAnswer(studenAnswer);
answer.setType(type);
answerList.add(answer);
}
}
returnanswerList;
}
/**
*将一个json字串转为list
*@paramprops
*@return
*/
publicstaticList<Answer>converAnswerFormString(Stringanswer){
if(answer==null||answer.equals(""))
returnnewArrayList();
JSONArrayjsonArray=JSONArray.fromObject(answer);
List<Answer>list=(List)JSONArray.toCollection(jsonArray,
Answer.class);
returnlist;
}
2. 将一个Answer对象的List生成Json字串,是根据客户端页面用户输入的信息生成的
publicStringgetAnswerString(String[]studenAnswers,int[]question_ids,
int[]types,int[]scores){
Listlist=toAnswerList(studenAnswers,question_ids,
types,scores);
JSONArrayjsonarray=JSONArray.fromObject(list);
returnjsonarray.toString();
}
PS:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/