java将json字符串转换实体bean,list

序列化表单中的数据,将表单中的数据转为实体bean,list

var formData = $("#theform").serializeArray();//序列化为JSON对象数组

var topicFlat = JSON.stringify(formData );//将JSON对象数组转为json字符串

后台java转换:

public JsonMsg addTopicFlat(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(value = "topic")String topic,
			@RequestParam(value = "topicFlat")String topicFlat) {
		
		JsonMsg msg = new JsonMsg();
		try {
			// 将topic json字符串先转为json对象,然后转为 TopicBean
			JSONObject topicObject = JSONObject.fromObject(topic);
			TopicBean topicBean = (TopicBean)JSONObject.toBean(topicObject, TopicBean.class);
			topicService.addTopic(topicBean);
			// 将topicFlat json字符串转为json对象数组,然后再转换为list
			JSONArray topicFlataArr = JSONArray.fromObject(topicFlat);
			@SuppressWarnings("unchecked")
			List topicFlataList = (List) JSONArray.toCollection(topicFlataArr, TopicFlatBean.class);
			for (TopicFlatBean topicFlatBean : topicFlataList) {
				Integer num = topicFlatBean.getRnumber();
				if(num != null) {
					topicFlatBean.setTopicId(topicBean.getId());
					topicFlatService.addTopicFlat(topicFlatBean);
				}
			}
			msg.setSuccess(true);
		} catch (Exception e) {
			msg.setSuccess(false);
			e.printStackTrace();
		}
		return msg;
	}

注意:

        这里使用的JSONObject为net.sf.json jar包里的

        并不是所有的表单提交,都需要转换为json字符串,然后后台再转为bean的。


你可能感兴趣的:(java将json字符串转换实体bean,list)