String转成JSON的实现

Posted pipicai96

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了String转成JSON的实现相关的知识,希望对你有一定的参考价值。

String转成JSON

这个依赖很重要,我们将围绕fastjson中的JSONObject这个类来谈转换

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.15</version>
    </dependency>
  1. String转成JSON
String json = "{"abc":"1","hahah":"2"}";
JSONObject jsonObject = JSONObject.parseObject(content);
一句话就能解决,非常便捷。
想要取出值,可以对`jsonObject`进行操作:
jsonObject.getString("abc");
结果为:`1`
  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);   
  1. 将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);
            }
        }
    }
}

以上是关于String转成JSON的实现的主要内容,如果未能解决你的问题,请参考以下文章

[C++]json cpp中将整个Json::Value转成std::string或者把里面值转成string类型

js中,怎么把object转成string?

[C++]jsoncpp中将整个Json::Value转成std::string或者把里面值转成string类型

怎么把json字符串转成数组对象

Android ---------List 数组转成 json格式的字符串

05 - json转成树状结构