• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

JSON的String字符串与Java的List列表对象的相互转换

java 搞代码 4年前 (2022-01-05) 32次浏览 已收录 0个评论

这篇文章主要介绍了JSON的String字符串与Java的List列表对象的相互转换,如果在浏览器端JSON是list则转为string结构来处理,需要的朋友可以参考下

在前端:
1.如果json是List对象转换的,可以直接遍历json,读取数据。
2.如果是需要把前端的List对象转换为json传到后台,param是ajax的参数,那么转换如下所示:

 var jsonStr = JSON.stringify(list); var param= {}; param.jsonStr=jsonStr; 

在后台:
1.把String转换为List(str转换为list)

 List li<strong style="color:transparent">来源gao@daima#com搞(%代@#码@网</strong>st = new ArrayList(); JSONArray jsonArray = JSONArray.fromObject(str);//把String转换为json list = JSONArray.toList(jsonArray,t);//这里的t是Class 

2.把List转换为json

 JSONArray json = JSONArray.fromObject(object); String str = json.toString();//把json转换为String 

eg:
1. 根据页面用户输入的信息形成 Answer 对象的List 

 /** * @param answers * @param question_ids * @param types * @return */ private List toAnswerList(String[] studenAnswers, int[] question_ids, int[] types,int[] scores) { List answerList = new ArrayList(); if(studenAnswers!=null && question_ids!= null && types!= null&& scores!= null){ for (int i = 0; i <studenAnswers.length; i++) { Answer answer = new Answer(); String studenAnswer = studenAnswers[i]; int type = types[i]; int question_id = question_ids[i]; int score = scores[i]; answer.setQuestion_id(question_id); answer.setScore(score); answer.setStudenAnswer(studenAnswer); answer.setType(type); answerList.add(answer); } } return answerList; } /** * 将一个json字串转为list * @param props * @return */ public static List converAnswerFormString(String answer){ if (answer == null || answer.equals("")) return new ArrayList(); JSONArray jsonArray = JSONArray.fromObject(answer); List list = (List) JSONArray.toCollection(jsonArray, Answer.class); return list; } 

2. 将一个 Answer 对象的List 生成Json字串,是根据客户端页面用户输入的信息生成的 

 public String getAnswerString(String[] studenAnswers, int[] question_ids, int[] types,int[] scores) { List list = toAnswerList(studenAnswers, question_ids, types, scores); JSONArray jsonarray = JSONArray.fromObject(list); return jsonarray.toString(); } 

 

PS:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具:
http://tools.gaodaima.com/code/json

JSON在线格式化工具:
http://tools.gaodaima.com/code/jsonformat

在线XML/JSON互相转换工具:
http://tools.gaodaima.com/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.gaodaima.com/code/jsoncodeformat

在线json压缩/转义工具:
http://tools.gaodaima.com/code/json_yasuo_trans

C语言风格/HTML/CSS/json代码格式化美化工具:
http://tools.gaodaima.com/code/ccode_html_css_json

以上就是JSON的String字符串与Java的List列表对象的相互转换的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:JSON的String字符串与Java的List列表对象的相互转换

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址