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

}
相关推荐
Wpa.wk12 小时前
性能测试工具 - JMeter工具组件介绍二
运维·经验分享·测试工具·jmeter·自动化·json
WindHunter61519 小时前
越是非标项目,越要先签“需求确认书”
经验分享·微信·制造·微信公众平台
Watermelo61719 小时前
探究TOON的价值边界:比JSON更优的大模型友好数据格式?
数据结构·人工智能·语言模型·自然语言处理·数据挖掘·数据分析·json
ID_1800790547320 小时前
除了Python,还有哪些语言可以解析淘宝商品详情API返回的JSON数据?
开发语言·python·json
Full Stack Developme20 小时前
达梦(DM8)对 JSON 与 XML 的使用教程
xml·数据库·json
全栈前端老曹2 天前
【包管理】npm init 项目名后底层发生了什么的完整逻辑
前端·javascript·npm·node.js·json·包管理·底层原理
黄金贼贼2 天前
2026最新java单元测试json校验器
java·单元测试·json
C_心欲无痕2 天前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
羊群智妍2 天前
跨境、合规、垂类全覆盖 2026 GEO五强服务商适配指南
百度·微信·微信公众平台·新浪微博·segmentfault
sheji34162 天前
【开题答辩全过程】以 微信小程网上书店为例,包含答辩的问题和答案
微信