根据微信返回的JSON生成 JavaBean

引入pom.xml

xml 复制代码
		<!--velocity代码生成使用模板 -->
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity</artifactId>
			<version>1.7</version>
		</dependency>
		<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-json</artifactId>
            <version>5.8.20</version>
        </dependency>

WxJavaBean

java 复制代码
import lombok.Data;
import java.util.List;

@Data
public class WxJavaBean {
    private String className;
    private String path;
    private List<WxField> fields;
}

WxField

java 复制代码
import lombok.Data;
@Data
public class WxField {
    private String path;
    private Integer type;
    private String jsonName;
    private String javaName;

}

java

java 复制代码
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.util.*;

public class AA {
    public static void main(String[] args) {
        String vmPathPre="D:\\xxxx\";
        String vmPathSfx="vm-local\\wx-java\\bean.java.vm";
        String packageName="com.xxx.wechat.dto.order.detail.rsp";
        String fileName="D:\\xxxxxx\\src\\main\\java\\wechat\\dto\\order\\detail\\rsp";
 			//微信返回的json
        String s="{}";
        String baseNameDTO="OrderDetailDTO";

        List<WxJavaBean> javaBeanFiles = new ArrayList<>();
        Stack<String>  fileNameStack = new Stack<>();
//        fileNameStack.push("OrderDetail");
        JSONObject jsonObject =null;
        JSON parse = JSONUtil.parse(s);
        String nowKeyPath=null;
        do{
            String pop = fileNameStack.isEmpty()?baseNameDTO: fileNameStack.pop();
//            System.out.println(pop);
            if(null==nowKeyPath && fileNameStack.isEmpty()){
                nowKeyPath="";
            }else {
                nowKeyPath=pop+".";
            }
            if(null==jsonObject){
                jsonObject = JSONUtil.parseObj(s);
            }else {
                String byPath = parse.getByPath(pop).toString();
                int i = byPath.indexOf("{");
                int length = byPath.length();
//                System.out.println("byPath  >> " + byPath);
                String subStr = StrUtil.sub(byPath, i, length - i);
//                System.out.println("subStr  >> " + subStr);
                try {
                    jsonObject =JSONUtil.parseObj(subStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            List<WxField> ll = new ArrayList<>();
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                WxField wxField = new WxField();
                String key = entry.getKey();
                wxField.setPath(key);
                String keyName=key;
                if(keyName.contains(".")){
                    int i = key.lastIndexOf(".");
                    keyName  = key.substring(i);
                }
                wxField.setJsonName(keyName);
                wxField.setJavaName(StrUtil.toCamelCase(keyName));
                Object value = entry.getValue();
                if(value instanceof Integer){
                    wxField.setType(0);
                } else if(value instanceof String){
                    wxField.setType(1);
                } else if(value instanceof Boolean){
                    wxField.setType(2);
                }else {
                    wxField.setType(3);
//                    System.out.println("push >>> "+nowKeyPath+key);
                    fileNameStack.push(nowKeyPath+key);
                }
                ll.add(wxField);
            }
            WxJavaBean wxJavaBean = new WxJavaBean();
            wxJavaBean.setPath(pop);
            String keyName=pop;
            if(keyName.contains(".")){
                int i = pop.lastIndexOf(".");
                keyName  = pop.substring(i+1);
            }

wxJavaBean.setClassName(StrUtil.upperFirst(StrUtil.toCamelCase(keyName) ));
            wxJavaBean.setFields(ll);
            javaBeanFiles.add(wxJavaBean);
//            System.out.println(ll);
        }while (!fileNameStack.empty());

            Properties p = new Properties();
            // 加载classpath目录下的vm文件
            p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,vmPathPre);
            // 定义字符集
            p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
            p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
            // 初始化Velocity引擎,指定配置Properties
            Velocity.init(p);

        for (WxJavaBean javaBeanFile : javaBeanFiles) {
            System.out.println(String.format("key >>> %s  ,  size >>> %d ",javaBeanFile.getPath(),javaBeanFile.getFields().size()) );
            List<WxField> fields = javaBeanFile.getFields();
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(vmPathSfx, "UTF-8");
            VelocityContext velocityContext = new VelocityContext();
            velocityContext.put("randomUID", RandomUtil.randomInt());
            velocityContext.put("fields",fields);
            velocityContext.put("ClassName",javaBeanFile.getClassName());
            velocityContext.put("packageName",packageName);
            tpl.merge(velocityContext, sw);
            FileUtil.writeUtf8String(sw.toString(),fileName+"\\"+javaBeanFile.getClassName()+".java");
//            System.out.println(sw.toString());

        }

    }
}
java 复制代码
import lombok.Data;
import java.util.List;

@Data
public class WxJavaBean {
    private String className;
    private String path;
    private List<WxField> fields;
}

bean.java.vm

java 复制代码
package ${packageName};

import cn.hutool.core.annotation.Alias;
import lombok.Data;
import java.io.Serializable;
import java.util.List;

@Data
public class ${ClassName} implements Serializable {

    private static final long serialVersionUID = ${randomUID}L;
#foreach ($column in $fields)
    @Alias("$column.jsonName")
    private #if($column.type == 0
)Integer#elseif($column.type == 1
)String#elseif($column.type == 2
)Boolean#elseif($column.type == 3
)#set($AttrName=$column.javaName.substring(0,1).toUpperCase() + ${column.javaName.substring(1)}
)List<$AttrName>#end $column.javaName;
#end

}
相关推荐
火车叨位去19495 小时前
Java中的JSON序列化和反序列化
json
测试杂货铺15 小时前
Jmeter(六):json断言元件,jmeter参数化实现
jmeter·json
二十十十十十19 小时前
微信点餐小程序—美食物
微信·小程序
专注VB编程开发20年20 小时前
C#,VB.NET从JSON数据里提取数组中的对象节点值
c#·json·.net
草履虫建模1 天前
Postman - API 调试与开发工具 - 标准使用流程
java·测试工具·spring·json·测试用例·postman·集成学习
奔跑的蜗牛AZ11 天前
TiDB 字符串行转列与 JSON 数据查询优化知识笔记
笔记·json·tidb
m0_6855350811 天前
如何实现财务自由
微信·新浪微博·光学·光学设计·光学工程
书虫AI11 天前
登顶生图榜前三!FLUX.1 Kontext 为什么把 PS 都逼急了?
微信
陈思杰系统思考Jason12 天前
系统思考VS心智模式
百度·微信·微信公众平台·新浪微博·微信开放平台
jarctique13 天前
java 找出两个json文件的不同之处
java·json