根据微信返回的JSON生成 JavaBean

引入pom.xml

		
		<dependency>
			<groupId>org.apache.velocitygroupId>
			<artifactId>velocityartifactId>
			<version>1.7version>
		dependency>
		<dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-jsonartifactId>
            <version>5.8.20version>
        dependency>

WxJavaBean

import lombok.Data;
import java.util.List;

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

WxField

import lombok.Data;
@Data
public class WxField {
    private String path;
    private Integer type;
    private String jsonName;
    private String javaName;

}

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());

        }

    }
}
import lombok.Data;
import java.util.List;

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

bean.java.vm

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

}

你可能感兴趣的:(微信小程序,微信,json)