我们将围绕fastjson中的JSONObject这个类来谈转换
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
String转成JSON
String json = "{"abc":"1","hahah":"2"}";
JSONObject jsonObject = JSONObject.parseObject(content);
一句话就能解决,非常便捷。
想要取出值,可以对`jsonObject`进行操作:
jsonObject.getString("abc");
结果为:`1`
将String转为list后转为JSON
List<String> list = new ArrayList<String>();
list.add("username");
list.add("age");
list.add("sex");
JSONArray array = new JSONArray();
array.add(list);
将String转为map后转为JSON
Map<String, String> map = new HashMap<String, String>();
map.put("abc", "abc");
map.put("def", "efg");
JSONArray array_test = new JSONArray();
array_test.add(map);
JSONObject jsonObject = JSONObject.fromObject(map);
特别注意:从JSONObject中取值,碰到了数字为key的时候,如
{
"userAnswer": {
"28568": {
"28552": {
"qId": "28552",
"order": "1",
"userScore": {
"score": 100
},
"answer": {
"28554": "28554"
},
"qScore": "100.0",
"qtype": "SingleChoice",
"sId": "28568"
}
}
},
"paperType": "1",
"paperOid": "28567",
"instanceId": 30823,
"remainingTime": -1,
"examOid": "28570"
}
获取“userAnswer”的value,再转成JSON,可仿照如下形式:
JSONObject userJson = JSONObject.parseObject(jsonObject.getString("userAnswer"));
但是想获取key"28568"就没这么容易了。直接像上述的写法,会报错。
我们浏览fastjson中的源码,总结下,应该如下写:
JSONObject question = (JSONObject) JSONObject.parseObject(section.getString("28568"), Object.class);
整体代码:
dao代码很容易,就不贴出来了。
package com.xiamenair.training.business.service;
import com.alibaba.fastjson.JSONObject;
import com.xiamenair.training.business.dao.elearningdao.ELearningExamInstanceDao;
import com.xiamenair.training.business.dao.masterdao.ELearningChoiceRecordDao;
import com.xiamenair.training.business.model.LasChoiceRecord;
import com.xiamenair.training.business.model.entity.elearning.LasExamInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class ChoiceRecordService {
//查询数据Dao
@Autowired
private ELearningChoiceRecordDao eLearningChoiceRecordDao;
//转储数据Dao
@Autowired
private ELearningExamInstanceDao eLearningExamInstanceDao;
private ChoiceRecordService() {
}
private static class SingletonRecordInstance {
private static final LasChoiceRecord choiceRecord = new LasChoiceRecord();
}
public static LasChoiceRecord getMapInstance() {
return SingletonRecordInstance.choiceRecord;
}
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
/**
* 定时任务,每天定时将E学网考试数据分析并转储
*
* @param : instanceIdList
* @return : void
* @author : 28370·皮育才
* @date : 2018/11/20
**/
@Scheduled(cron = "00 00 01 * * ?")
public void analysisChoiceRecord() {
//获取前一天的时间
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(calendar.DATE, -1);
date = calendar.getTime();
String dateString = simpleDateFormat.format(date);
List<BigDecimal> instanceIdList = eLearningExamInstanceDao.findInstanceIdByFinishTime(dateString);
if(0 != instanceIdList.size()){
LasChoiceRecord lasChoiceRecord = getMapInstance();
instanceIdList.stream().forEach(instanceId -> {
Blob answerBlob = eLearningExamInstanceDao.findUserAnswer(instanceId);
Long userId = eLearningExamInstanceDao.findUserId(instanceId);
String content = null;
try {
content = new String(answerBlob.getBytes((long) 1, (int) answerBlob.length()));
} catch (SQLException e) {
e.printStackTrace();
System.out.println("SQLEXCEPTION:" + e);
}
JSONObject jsonObject = JSONObject.parseObject(content);
//针对本section的"公共"属性直接设置
lasChoiceRecord.setUserId(userId);
lasChoiceRecord.setPaperType(jsonObject.getString("paperType"));
lasChoiceRecord.setPaperId(jsonObject.getString("paperOid"));
lasChoiceRecord.setExamInstanceId(jsonObject.getString("instanceId"));
lasChoiceRecord.setRemainingTime(jsonObject.getString("remainingTime"));
lasChoiceRecord.setExamId(jsonObject.getString("examOid"));
//针对section中的题目进行细化循环拆分
JSONObject userJson = JSONObject.parseObject(jsonObject.getString("userAnswer"));
Set sectionSet = userJson.keySet();
Iterator<String> setIt = sectionSet.iterator();
analyzeAnswer(lasChoiceRecord, userJson, setIt);
});
}
}
private void analyzeAnswer(LasChoiceRecord lasChoiceRecord, JSONObject userJson, Iterator<String> setIt) {
while (setIt.hasNext()) {
//对每个question进行再次拆分出题目
JSONObject section = (JSONObject) JSONObject.parseObject(userJson.getString(setIt.next()), Object.class);
Set questionSet = section.keySet();
Iterator<String> queIt = questionSet.iterator();
while (queIt.hasNext()) {
JSONObject question = (JSONObject) JSONObject.parseObject(section.getString(queIt.next()), Object.class);
String userAnswer = question.getString("answer");
String userScore = question.getString("userScore");
lasChoiceRecord.setQuestionId(question.getString("qId"));
lasChoiceRecord.setRecordId(UUID.randomUUID().toString());
eLearningChoiceRecordDao.save(lasChoiceRecord);
}
}
}
}
最近研究java的东西。之前靠着自己的摸索,实现了把java对象转成json格式的数据的功能,返回给前端。当时使用的是 JSONObject.fromObject(object) 方法把java对象换成json格式。也就是先有一个java实体类,例如叫User。然后从数据库查出列表数据,也就是一个List,里面的每一条数据都是一个User的实体对象。而如果前端需求变化,需要在当前这个接口中多返回一个字段时,就需要修改这个User实体类,新增字段。这样一来,所有用到这个User实体类的接口的地方,接口返回的json数据里都会有新增的这个字段。后来发现可以用一下方法根据需要动态拼接需要的字段。
package com.lin.domain;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) throws Exception {
JSONObject createJSONObject = createJSONObject();
System.out.println(createJSONObject);
}
// 创建JSONObject对象
private static JSONObject createJSONObject() {
JSONObject result = new JSONObject();
result.put("success", true);
result.put("totalCount", "30");
JSONObject user1 = new JSONObject();
user1.put("id", "12");
user1.put("name", "张三");
user1.put("createTime", "2017-11-16 12:12:12");
JSONObject user2 = new JSONObject();
user2.put("id", "13");
user2.put("name", "李四");
user2.put("createTime", "2017-11-16 12:12:15");
JSONObject department = new JSONObject();
department.put("id", 1);
department.put("name","技术部");
user1.put("department", department);
user2.put("department", department);
// 返回一个JSONArray对象
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, user1);
jsonArray.add(1, user2);
result.element("data", jsonArray);
return result;
}
}
返回的Json数据:
下面是真实的接口代码,从数据库中查询数据:
@ResponseBody
@RequestMapping(value="/getRoleMenuList.do", method=RequestMethod.GET)
public void getRoleMenuList(HttpServletRequest req, HttpServletResponse res, Integer roleId) throws IOException{
res.setHeader("Content-type", "application/json;charset=UTF-8");
res.setCharacterEncoding("UTF-8");
ResListData rld = new ResListData();
JSONObject result = new JSONObject();
try {
Map<String, Object> params1 = new HashMap<>();
params1.put("roleId", roleId);
params1.put("menuLevel", 1);
List<RoleJuri> fMenuList = rjService.getRoleMenuList2(params1); //一级菜单
JSONArray firstList = new JSONArray();
for(int i=0; i<fMenuList.size(); i++){
RoleJuri firstMenu = fMenuList.get(i);
JSONObject firstResult = new JSONObject();
firstResult.put("id", firstMenu.getId());
firstResult.put("name", firstMenu.getMenuName());
firstResult.put("url", firstMenu.getMenuUrl());
Map<String, Object> params2 = new HashMap<>();
params2.put("roleId", roleId);
params2.put("menuPId", firstMenu.getMenuId());
List<RoleJuri> sMenuList = rjService.getRoleMenuList2(params2); //二级菜单
JSONArray secondList = new JSONArray();
for(int j=0; j<sMenuList.size(); j++){
RoleJuri secondMenu = sMenuList.get(j);
JSONObject secondResult = new JSONObject();
secondResult.put("id", secondMenu.getId());
secondResult.put("name", secondMenu.getMenuName());
secondResult.put("url", secondMenu.getMenuUrl());
secondList.add(secondResult);
}
firstResult.put("children", secondList);
firstList.add(firstResult);
}
if(fMenuList.size() > 0){ //查询到了一级菜单
result.put("success", 1);
result.put("data", firstList);
}else{ //未查询到一级菜单
result.put("success", 0);
result.put("data", new Array());
result.put("error", "未获取到菜单数据");
}
} catch (Exception e) {
result.put("success", 0);
result.put("data", new Array());
result.put("error", "服务器运行错误");
}
res.getWriter().write(result.toString());
}
返回的Json数据:
参考:
https://www.cnblogs.com/libo0125ok/p/7905665.html
https://blog.csdn.net/javaQQ561487941/article/details/84328669
https://www.cnblogs.com/LearnAndGet/p/10009646.html