首页 > 作文

MySQL读取JSON转换的方式

更新时间:2023-04-06 04:47:35 阅读: 评论:0

存储

mysql5.7+开始支持存储json,后续不断优化,应用也越来越广泛你可以自己将数据转换成json string后插入,也可以选择使用工具,而mybatis-plus就为此提供了非常简便的方式,只需要在字段上加上 @tablefield(typehandler = xxxtypehandler.class),mybatis-plus就会自动帮你做转换,通用一般就两个:   - com.baomidou.mybatisplus.extension.handlers.jacksontypehandler   - com.baomidou.mybatisplus.extension.handlers.fastjsontypehandler

例如

@data@tablename(autoresultmap = true)public class department implements rializable {    private static final long rialversionuid = 203788572415896870l;    @tablefield(typehandler = fastjsontypehandler.class)    private list<integer> urids;}

存在什么问题?

如果使用通用处理器,那对于基础类型以及对象来说没有什么问题。但如果存储的字段类型是对象集合,那么当你取出来时,会发现集合中的对象都是jsonobject类型。最常见的情况就拿出来进行遍历操作时,会抛出强转异常:    java.lang.classcastexception: com.alibaba.fastjson.jsonobject cannot be cast to ...因为处理器帮你转换时,并不会存储你集合的泛型,所以统统都按照object类型来转换了:    @override    protected object par(strin真的伤不起g json) {        return json.parobject(json, type);    }

例如下面这种形式的类:

@data@tablename(autoresultmap = true)public class department implements rializable {    private static final long rialversionuid = 203788572415896870l;    @tableid(value = "id", type = idtype.auto)    private integer id;    @tablefield(typehandler = fastjsontypehandler.class)    private list<ur> urs;    @data    public static class ur implements rializable {        // ...    }}

如何处理

方式一:自定义处理器,自己做类型转换,这也是当前最普遍的方式,但是对于存在list字段的对象,还需要在xxxmapper.xml中进行resultmap配置

@mappedtypes({object.class})@mappedjdbctypes(jdbctype.varchar)public class listfastjsontypehandler extends fastjsontypehandler {    private final class<? ex难忘的生日作文tends object> type;    public listfastjsontypehandler(class<?> type) {        super(type);        this.type = type;    }    /**     * 自己将json转换成list     * @param json     * @return     */    @override    protected object par(string json) {        return json.pararray(json, this.type);}
<mapper namespace="com.xxx.cn.mapper.departmentmapper">    <resultmap id="baresultmap" type="com.xxx.cn.domain.department">        <id property="id" column="id"/>        <result property="urs" column="urs" jdbctype="varchar"                javatype="com.xxx.cn.domain.department.ur"                typehandler="com.baomidou.mybatisplus.extension.handlers.fastjsontypehandler"/>    </resultmap></mapper>

配置完成后,listfastjsontypehandler就会将json转换成javatype对应的对象集合了

方式二:配置一个mybatis插件,拦截resultthandler,将返回结果进行处理。 这样的好处就是不用写自定义的处理器和在xxxmapper.xml中做配置,减少了工作

@component@intercepts({        @signature(type = resultthandler.class, method = "handleresultts", args = {statement.class})})public class resulttinterceptor implements interceptor {    /**     * json序列化规则     */    private final rializerfeature[] rializerfeatures = {            rializerfeature.writemapnullvalue,            rializerfeature.writenulllistampty,            rializerfeature.writenullstringampty    };    @override    public object intercept(invocation invocation) throws throwable {        object proceed = invocation.proceed();        if (containjsonobject(proceed)) {            if (proceed instanceof collection) {                return json.pararray(json.tojsonstring(proceed, rializerfeatures), ((collection<?>) proceed).toarray()[0].getclass());            }            return json.parobject(json.tojsonstring(proceed, rializerfeatures), proceed.getclass());        }//        if (proceed instanceof collection) {//            for (object obj : ((collection<?>) proceed)) {//                parjson2object(obj, obj.getclass());//            }//        } el {//            parjson2object(proceed, proceed.getclass());// 谜语及答案大全       }        return proceed;    }     * 将返回数据中心的jsonobject对象转换成正常的对象     *     * @param obj     * @param typeclass     * @throws illegalaccesxception     * @throws classnotfoundexception    private void parjson2object(object obj, class<?> typeclass) throws illegalaccesxception, classnotfoundexception {        for (field declaredfield : typeclass.getdeclaredfields()) {            declaredfield.taccessible(true);            object value = declaredfield.get(obj);            if (isnullvaluefield(value)) {                continue;            type generictype = declaredfield.getgenerictype();            string fieldclassname = generictype.gettypename();            if (generictype instanceof parameterizedtype) {                fieldclassname = ((parameterizedtype) generictype).getactualtypearguments()[0].gettypename();            if (containjsonobject(value)) {                if (value instanceof collection) {                    declaredfield.t(obj, json.pararray(json.tojsonstring(value, riali我爱我的家乡 作文zerfeatures), class.forname(fieldclassname)));                } el {                    declaredfield.t(obj, json.parobject(json.tojsonstring(value, rializerfeatures), class.forname(fieldclassname)));                }     * 判断是否跳过字段     * @param value     * @return    private boolean isnullvaluefield(object value) {        return null == value || "".equals(string.valueof(value).trim())                || (value instanceof collection && ((collection<?>) value).size() == 0);     * 判断值是否包含jsonobject对象    private boolean containjsonobject(object value) throws illegalaccesxception {        if (isnullvaluefield(value)) {            return fal;        if (value instanceof collection) {            for (object obj : (collection<?>) value) {                if (obj instanceof jsonobject) {                    return true;                if (obj instanceof collection && containjsonobject(obj)) {                    for (field declaredfield : obj.getclass().getdeclaredfields()) {                        declaredfield.taccessible(true);                        object fieldvalue = declaredfield.get(obj);                        if (isnullvaluefield(fieldvalue)) {                            continue;                        }                        if (fieldvalue instanceof jsonobject) {                            ret高中语文作文素材大全urn true;                        if (fieldvalue instanceof collection && containjsonobject(fieldvalue)) {                    }        return value instanceof jsonobject;}

到此这篇关于mysql读取json转换的文章就介绍到这了,更多相关mysql读取json转换内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

本文发布于:2023-04-06 04:47:33,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/82b469cf0eb658f939f87533ddecf720.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:MySQL读取JSON转换的方式.doc

本文 PDF 下载地址:MySQL读取JSON转换的方式.pdf

下一篇:返回列表
标签:对象   字段   转换成   类型
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图