• 使用JSON字符串生成Java实体类


    使用JSON字符串生成Java实体类

    引子

    当我们和JSON数据交互的时候,有时候就需要将JSON数据转成实体来操作的情况,这个时候,字段少还好,字段一多,我们手动创建就很麻烦了.有的同学就说了,IDEA有插件啊,插件好用的很.但是我就是想不安装插件,通过一个copy然后执行一下就能把实体生成出来了,这个时间比找插件安装重启项目要快吧,而且还是透明的,想要改哪个地方也方便,下面来看看我写的相关代码!

    核心类JsonToEntity

    
    import com.alibaba.fastjson.JSONObject;
    import com.xxj.demo.json.util.CustomIOUtil;
    import org.apache.commons.lang3.ObjectUtils;
    import org.apache.commons.lang3.StringUtils;
    
    import java.util.*;
    
    /**
     * 将json格式字符串生成出实体字段
     *
     * @author xunjian.xiao
     * @date 2022/11/11 15:51
     */
    
    public class JsonToEntity {
        /**
         * 结果字符串
         */
        private StringBuilder resultString = new StringBuilder("\n");
    
        /**
         * 给json的key-设置属性名
         */
        private Map<String, String> fieldMap = new HashMap<>(16);
    
        /**
         * 给json的key-设置属性名
         *
         * @param key
         * @param value
         */
        public void fieldMapPut(String key, String value) {
            this.fieldMap.put(key, value);
        }
    
        /**
         * 给json的key-设置说明
         */
        private Map<String, String> fieldDescriptionMap = new HashMap<>(16);
    
        /**
         * 给json的key-设置说明
         *
         * @param key
         * @param value
         */
        public void fieldDescriptionMapPut(String key, String value) {
            this.fieldDescriptionMap.put(key, value);
        }
    
    
        /**
         * 需要追加的注解,规则:{key}-为json中的key,{value}-为json中的value 
    * 例如:
    * "@ExcelImport(value = \"{key}\",kv = \"\",required = true,maxLength = 255,unique = true)" */
    private List<String> appendInterfaceList = new ArrayList<>(16); public void appendInterfaceAdd(String interfaceStr) { this.appendInterfaceList.add(interfaceStr); } /** * 将json字符串转换成实体对象 * * @param clazz class对象 * @param classDescription 对象说明 * @param json json字符串 * @author xunjian.xiao * @date 2022/11/14 11:06 */ public void toEntityOrUpdateFile(Class clazz, String classDescription, String json) { String result = toEntity(clazz, classDescription, json); CustomIOUtil.rewriteFirst(clazz, null, result); } /** * 默认开启Lombok,swagger * * @param clazz class对象 * @param classDescription 对象说明 * @param json json字符串 * @return 生成结果字符串 * @author xunjian.xiao * @date 2022/11/14 9:23 */ public String toEntity(Class clazz, String classDescription, String json) { return toEntity(clazz, classDescription, true, true, json); } /** * 将json字符串转换成实体对象 * * @param clazz class对象 * @param classDescription 对象说明 * @param swagger 是否开启swagger注释 默认关闭 swagger说明 * @param lombok 是否开启lombok简化代码 默认关闭 lombok 代码简化 * @param json json字符串 * @return * @throws * @author xunjian.xiao * @date 2022/11/11 17:09 */ public String toEntity(Class clazz, String classDescription, Boolean swagger, Boolean lombok, String json) { if (clazz == null) { System.out.println("请选择对象"); return null; } if (swagger == null) { swagger = false;//默认关闭 swagger说明 } if (lombok == null) { lombok = false;//默认关闭 lombok 代码简化 } if (lombok) { resultString.append("@Data\n" + "@Accessors(chain = true)"); } if (swagger) { resultString.append("@ApiModel(value = \"" + clazz.getSimpleName() + "\", description = \"" + classDescription + "\")\n"); } resultString.append("public class " + clazz.getSimpleName() + "{\n"); Map<String, Object> stringStringMap = JSONObject.parseObject(json, Map.class); for (Map.Entry<String, Object> entity : stringStringMap.entrySet()) { resultString.append("\t"); String key = entity.getKey(); Object value = ""; if (ObjectUtils.isNotEmpty(entity.getValue())) { value = entity.getValue(); } String fieldDescription = fieldDescriptionMap.get(key); String field = fieldMap.get(key); field = Objects.isNull(field) ? key : field; if (Objects.nonNull(fieldDescription)) { //有说明 key = fieldDescription; } //注释 resultString.append(String.format("/**%s*/\n", key)); //扩展功能,追加注解 addInterface(key, value); if (swagger) { resultString.append("\t"); resultString.append(String.format("@ApiModelProperty(\"%s\")", key)); resultString.append("\n"); } //校验格式 String type = typeHandle(key, value); resultString.append("\t"); resultString.append(String.format("private %s %s;", type, field)); resultString.append("\n"); } resultString.append("}"); return resultString.toString(); } /** * 字段类型格式处理 * * @param key * @param value * @return {@link String} * @throws * @author xunjian.xiao * @date 2022/11/14 9:22 */ private String typeHandle(String key, Object value) { String type = getType(value); //if (key.contains("时间")) { //type = LocalDateTime.class.getSimpleName(); //String a = String.format("@JsonFormat( pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n\t@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")"); //resultString.append("\t"); //resultString.append(a); //resultString.append("\n"); //} return type; } /** * 添加要增加的注解 */ private void addInterface(String key, Object value) { for (String appendInterface : appendInterfaceList) { resultString.append("\t"); appendInterface = appendInterface.replace("{key}", key); appendInterface = appendInterface.replace("{value}", Objects.nonNull(value) ? value.toString() : StringUtils.EMPTY); resultString.append(appendInterface); resultString.append("\n"); } } /** * 类型判断 * * @param value 值 * @return {@link String} * @throws * @author xunjian.xiao * @date 2022/11/11 15:57 */ private String getType(Object value) { //默认字符串格式 String type = String.class.getSimpleName(); if (value != null) { type = value.getClass().getSimpleName(); } return type; } /** * 打印json格式相关功能字符串 * * @param json * @author xunjian.xiao * @date 2022/11/14 11:27 */ public static void prlintlnJsonMap(String json) { Map<String, Object> stringObjectMap = JSONObject.parseObject(json, Map.class); int i = 97; for (Map.Entry<String, Object> a : stringObjectMap.entrySet()) { System.out.println(String.format("jsonToEntity.fieldMapPut(\"%s\",\"%c\");", a.getKey(), i++)); } } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243

    将json格式字符串生成出实体字段CustomIOUtil

    package com.xxj.demo.json;
    
    import com.alibaba.fastjson.JSONObject;
    import com.xxj.demo.json.util.CustomIOUtil;
    import org.apache.commons.lang3.ObjectUtils;
    import org.apache.commons.lang3.StringUtils;
    
    import java.util.*;
    
    /**
     * 将json格式字符串生成出实体字段
     *
     * @author xunjian.xiao
     * @date 2022/11/11 15:51
     */
    
    public class JsonToEntity {
        /**
         * 结果字符串
         */
        private StringBuilder resultString = new StringBuilder("\n");
    
        /**
         * 给json的key-设置属性名
         */
        private Map<String, String> fieldMap = new HashMap<>(16);
    
        /**
         * 给json的key-设置属性名
         *
         * @param key
         * @param value
         */
        public void fieldMapPut(String key, String value) {
            this.fieldMap.put(key, value);
        }
    
        /**
         * 给json的key-设置说明
         */
        private Map<String, String> fieldDescriptionMap = new HashMap<>(16);
    
        /**
         * 给json的key-设置说明
         *
         * @param key
         * @param value
         */
        public void fieldDescriptionMapPut(String key, String value) {
            this.fieldDescriptionMap.put(key, value);
        }
    
    
        /**
         * 需要追加的注解,规则:{key}-为json中的key,{value}-为json中的value 
    * 例如:
    * "@ExcelImport(value = \"{key}\",kv = \"\",required = true,maxLength = 255,unique = true)" */
    private List<String> appendInterfaceList = new ArrayList<>(16); public void appendInterfaceAdd(String interfaceStr) { this.appendInterfaceList.add(interfaceStr); } /** * 将json字符串转换成实体对象 * * @param clazz class对象 * @param classDescription 对象说明 * @param json json字符串 * @author xunjian.xiao * @date 2022/11/14 11:06 */ public void toEntityOrUpdateFile(Class clazz, String classDescription, String json) { String result = toEntity(clazz, classDescription, json); CustomIOUtil.rewriteFirst(clazz, null, result); } /** * 默认开启Lombok,swagger * * @param clazz class对象 * @param classDescription 对象说明 * @param json json字符串 * @return 生成结果字符串 * @author xunjian.xiao * @date 2022/11/14 9:23 */ public String toEntity(Class clazz, String classDescription, String json) { return toEntity(clazz, classDescription, true, true, json); } /** * 将json字符串转换成实体对象 * * @param clazz class对象 * @param classDescription 对象说明 * @param swagger 是否开启swagger注释 默认关闭 swagger说明 * @param lombok 是否开启lombok简化代码 默认关闭 lombok 代码简化 * @param json json字符串 * @return * @throws * @author xunjian.xiao * @date 2022/11/11 17:09 */ public String toEntity(Class clazz, String classDescription, Boolean swagger, Boolean lombok, String json) { if (clazz == null) { System.out.println("请选择对象"); return null; } if (swagger == null) { swagger = false;//默认关闭 swagger说明 } if (lombok == null) { lombok = false;//默认关闭 lombok 代码简化 } if (lombok) { resultString.append("@Data\n" + "@Accessors(chain = true)"); } if (swagger) { resultString.append("@ApiModel(value = \"" + clazz.getSimpleName() + "\", description = \"" + classDescription + "\")\n"); } resultString.append("public class " + clazz.getSimpleName() + "{\n"); Map<String, Object> stringStringMap = JSONObject.parseObject(json, Map.class); for (Map.Entry<String, Object> entity : stringStringMap.entrySet()) { resultString.append("\t"); String key = entity.getKey(); Object value = ""; if (ObjectUtils.isNotEmpty(entity.getValue())) { value = entity.getValue(); } String fieldDescription = fieldDescriptionMap.get(key); String field = fieldMap.get(key); field = Objects.isNull(field) ? key : field; if (Objects.nonNull(fieldDescription)) { //有说明 key = fieldDescription; } //注释 resultString.append(String.format("/**%s*/\n", key)); //扩展功能,追加注解 addInterface(key, value); if (swagger) { resultString.append("\t"); resultString.append(String.format("@ApiModelProperty(\"%s\")", key)); resultString.append("\n"); } //校验格式 String type = typeHandle(key, value); resultString.append("\t"); resultString.append(String.format("private %s %s;", type, field)); resultString.append("\n"); } resultString.append("}"); return resultString.toString(); } /** * 字段类型格式处理 * * @param key * @param value * @return {@link String} * @throws * @author xunjian.xiao * @date 2022/11/14 9:22 */ private String typeHandle(String key, Object value) { String type = getType(value); //if (key.contains("时间")) { //type = LocalDateTime.class.getSimpleName(); //String a = String.format("@JsonFormat( pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n\t@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")"); //resultString.append("\t"); //resultString.append(a); //resultString.append("\n"); //} return type; } /** * 添加要增加的注解 */ private void addInterface(String key, Object value) { for (String appendInterface : appendInterfaceList) { resultString.append("\t"); appendInterface = appendInterface.replace("{key}", key); appendInterface = appendInterface.replace("{value}", Objects.nonNull(value) ? value.toString() : StringUtils.EMPTY); resultString.append(appendInterface); resultString.append("\n"); } } /** * 类型判断 * * @param value 值 * @return {@link String} * @throws * @author xunjian.xiao * @date 2022/11/11 15:57 */ private String getType(Object value) { //默认字符串格式 String type = String.class.getSimpleName(); if (value != null) { type = value.getClass().getSimpleName(); } return type; } /** * 打印json格式相关功能字符串 * * @param json * @author xunjian.xiao * @date 2022/11/14 11:27 */ public static void prlintlnJsonMap(String json) { Map<String, Object> stringObjectMap = JSONObject.parseObject(json, Map.class); int i = 97; for (Map.Entry<String, Object> a : stringObjectMap.entrySet()) { System.out.println(String.format("jsonToEntity.fieldMapPut(\"%s\",\"%c\");", a.getKey(), i++)); } } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244

    获取Java项目路径工具类 JavaProjectPathUtil

    package com.xxj.demo.json.util;
    
    import java.io.File;
    import java.io.IOException;
    import java.net.URL;
    
    /**
     * 获取Java项目路径
     *
     * @author xunjian.xiao
     * @date 2022/11/11 14:57
     */
    
    public class JavaProjectPathUtil {
        /**
         *  获取当前类的所在工程真实路径
         * @param clazz
         * @return {@link String}
         * @author xunjian.xiao
         * @date 2022/11/14 9:35
         */
        public static String getPath(Class clazz){
            return clazz.getResource("").getPath().replace("target/classes","src/main/java")+File.separator+clazz.getSimpleName()+".java";
        }
    
        /**
         * 获取类加载的根路径
         * @param
         * @return {@link String}
         * @author xunjian.xiao
         * @date 2022/11/11 14:58
         */
        public String getProjectPathUrl(){
            // 第一种:获取类加载的根路径   D:\git\daotie\daotie\target\classes
            File f = new File(this.getClass().getResource("/").getPath());
            System.out.println("获取类加载的根路径:"+this.getClass().getResource("/").getPath());
            System.out.println(f);
    
            // 获取当前类的所在工程路径; 如果不加“/”  获取当前类的加载目录  D:\git\daotie\daotie\target\classes\my
            File f2 = new File(this.getClass().getResource("").getPath());
            System.out.println("获取当前类的加载目录:"+this.getClass().getResource("").getPath());
            System.out.println(f2);
    
            // 第二种:获取项目路径    D:\git\daotie\daotie
            File directory = new File("");// 参数为空
            String courseFile = null;
            try {
                courseFile = directory.getCanonicalPath();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(courseFile);
    
    
            // 第三种:  file:/D:/git/daotie/daotie/target/classes/
            URL xmlpath = this.getClass().getClassLoader().getResource("");
            System.out.println(xmlpath);
    
    
            // 第四种: D:\git\daotie\daotie
            System.out.println(System.getProperty("user.dir"));
            /*
             * 结果: C:\Documents and Settings\Administrator\workspace\projectName
             * 获取当前工程路径
             */
            // 第五种:  获取所有的类路径 包括jar包的路径
            System.out.println(System.getProperty("java.class.path"));
    
            return null;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    使用方式

    public class DemoApplication {
        public static void main(String[] args) {
            JsonToEntity jsonToEntity = new JsonToEntity();
    
            //可选:按需要在字段属性上追加的注解
            jsonToEntity.appendInterfaceAdd("@ExcelImport(value = \"{key}\",required = true,unique = true)");
             //可选:按需要重写属性名
            jsonToEntity.fieldMapPut("身份证号码","a");
            //User.class这个类需要手动先创建,创建后执行即可写入字段属性
            jsonToEntity.toEntityOrUpdateFile(User.class,"用户信息","这里是json格式数据字符串");
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • 相关阅读:
    uniapp获取视频第一帧作为封面图
    双指针解题
    Mybatis-plus的介绍与使用
    Pandas中常用属性和方法汇总
    并发安全问题之--事物失效问题
    SQL的约束
    java面试(缓存Redis)
    设计模式:03-单例模式
    Python库之pandas的简介、安装、使用方法详细攻略
    快来体验快速通道,netty中epoll传输协议详解
  • 原文地址:https://blog.csdn.net/qq_41915181/article/details/128186430