根据微信返回的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

}
相关推荐
譕痕3 天前
JSONObject与JSONArray封装数据格式区别
java·json
A黄俊辉A3 天前
uniapp webview中实现 app和内嵌的H5双向通信
vue.js·json
微信开发api3 天前
微信iPad协议怎么用?基于协议的二次开发实践
微信·机器人·ipad
wechatbot8883 天前
极客互动企业微信 SCRM 自动运营平台效果实测
java·微信·企业微信·rpa
懂软件的胡子个哥3 天前
微信机器人为什么需要“回复候选”而不是所有 AI 内容直接发送
运维·微信·自动化·wechatapi·个人微信号二次开发
伞伞悦读3 天前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json
Mikko73 天前
jackson-databind 升到 2.21.6 就安全了吗?jackson-core 是另一个坐标,它那条 high 全局库至今没收
java·后端·安全·json
微信开发api3 天前
微信机器人接口:REST API vs WebSocket 选型建议
微信·机器人·ipad
极客互动API3 天前
极客互动-企业微信基于外部API接口实现AI客服自动接管外部联系人消息收发
java·微信·企业微信·ai编程·rpa
随性而行3603 天前
企业微信二次开发实战:基于企业微信API构建自动化营销触达系统
微信