springboot+mybatis和FastJson解析数据库中的Json字段

导入依赖项:pom.xml


        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            com.alibaba
            fastjson
            1.2.78
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            3.0.0
        

注:使用mybatis注解,使用了lombok插件

数据表:

        

创建handler类:JsonTypeHandler (直接复制)



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.micrometer.common.util.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JsonTypeHandler extends BaseTypeHandler {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSONObject jsonObject, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, jsonObject.toJSONString());
    }

    @Override
    public JSONObject getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String jsonStr = resultSet.getString(s);
        return StringUtils.isBlank(jsonStr) ? null : JSON.parseObject(jsonStr);
    }

    @Override
    public JSONObject getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String jsonStr = resultSet.getString(i);
        return StringUtils.isBlank(jsonStr) ? null : JSON.parseObject(jsonStr);
    }

    @Override
    public JSONObject getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String jsonStr = callableStatement.getString(i);
        return StringUtils.isBlank(jsonStr) ? null : JSON.parseObject(jsonStr);
    }
}

yml配置文件:

spring:
  datasource:
    username: 账户
    password: 密码
    url: jdbc:mysql://localhost:3306/数据库?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  type-handlers-package: com.lujie.springboot04.utils.handler.JsonTypeHandler

 创建两个类:

        第一个类对应数据库中的字段名:JsonDataUtil 



import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class JsonDataUtil {
    private int id;
    private int questionId;
    private String questionName;
    private JSONObject questionText;
}

        创建第二个类对应json文件中的key:JsonParse 



import lombok.Data;

@Data
public class JsonParse {
    private String name;
    private String answerA;
    private String answerB;
    private String answerC;
    private String answer;

    public JsonParse(String name, String answerA, String answerB, String answerC, String answer) {
        this.name = name;
        this.answerA = answerA;
        this.answerB = answerB;
        this.answerC = answerC;
        this.answer = answer;
    }
    // {
    //        "name": "在数据结构中,从逻辑上可以把数据结构分成",
    //        "answerA": "线性结构和非线性结构",
    //        "answerB": "动态结构和静态结构",
    //        "answerC": "内部结构和外部结构",
    //        "answer": "A"
    //    }
}

dao层数据库接口:

import com.lujie.springboot04.pojo.utils.JsonDataUtil;
import com.lujie.springboot04.utils.handler.JsonTypeHandler;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
@Component
public interface JsonDao {
    @Select("select * from questioninf where questionId like #{questionId}")
    @Results(value = {
            @Result(property = "questionId",column = "questionId"),
            @Result(property = "questionName",column = "questionName"),
            @Result(property = "questionText",column = "questionText",typeHandler = JsonTypeHandler.class)

    })
    List jsonList(@Param("questionId") int questionId);
}
//typehandler使用刚才创建的handler类

service层:

        接口:JsonService

                

import com.lujie.springboot04.pojo.utils.JsonDataUtil;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface JsonService {
    List jsonList(@Param("questionId") int questionId);
}

        实现:JsonServiceImpl 

import com.lujie.springboot04.dao.JsonDao;
import com.lujie.springboot04.pojo.utils.JsonDataUtil;
import com.lujie.springboot04.service.JsonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class JsonServiceImpl implements JsonService {
    @Autowired
    private JsonDao jsonDao;

    public void setJsonDao(JsonDao jsonDao) {
        this.jsonDao = jsonDao;
    }

    @Override
    public List jsonList(int questionId) {
        return jsonDao.jsonList(questionId);
    }
}

准备工作已完成,进行代码编写:

        

@SpringBootTest
class SpringBoot04ApplicationTests {
    @Autowired
    JsonServiceImpl jsonService;
    @Test
    void contextLoads() {
        List jsonDataUitlList =jsonService.jsonList(2);
        //运行dao层sql查询语句, 并获取其值
        var map = new HashMap();
        //利用双列集合获取json文件
        System.out.println(jsonDataUitlList);
        int i=0;
        for (JsonDataUtil jsonDataUtil:jsonDataUitlList){
            JSONObject text=jsonDataUtil.getQuestionText();
            System.out.println(text);
            map.put(i,(new JsonParse(text.getString("name"),
                    text.getString("answerA"),
                    text.getString("answerB"),
                    text.getString("answerC"),
                    text.getString("answer"))));
            //将json的值,按照JsonParse类中的构造函数,一一对应放入
            i++;
        }
        //使用foreach
        System.out.println(map);
        Collection list=map.values();
        //将值赋给单列集合
        System.out.println(list);
        for (JsonParse jsonParse:list){
            System.out.println(jsonParse.getAnswer());
        }
        //数据展示

 

运行效果如封面:

        springboot+mybatis和FastJson解析数据库中的Json字段_第1张图片感谢您的阅读,希望能帮助您

你可能感兴趣的:(java框架,spring,boot,mybatis,json)