场景:最近研究gitlab的api,通过postget json对象的方式去新建或修改项目、组、钩子等操作,其json对象需要大量的key-value属性,
新建一个项目类需要一个个敲属性感觉十分繁琐,就写了这样一个工具,将json对象输出为JAVA类的属性,直接复制粘贴就能创建类。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
/**
* 将json对象输出为java类属性,不是实例
* @param jsonString json对象内容
* @author Mr.Xu
* @date 2020/7/13 0013
*/
public static void jsonToJavaObject(String jsonString){
// 使用map存储解析后的json对象
Map<String, Object> params = JSON.parseObject(jsonString, new TypeReference<Map<String, Object>>(){});
Iterator iterator = params.entrySet().iterator();
String obj;
String[] ss;
while (iterator.hasNext()){
obj = iterator.next().toString();
// value不为null的,获取其类型
if (params.get(obj.split("=")[0]) != null){
// 以.分割需要转义\.否则是通配符
ss = params.get(obj.split("=")[0]).getClass().getName().split("\.");
System.out.println(ss[ss.length-1]+" "+obj.split("=")[0]);
}else {
// value为null的,暂定为Object类
System.out.println("Object "+obj.split("=")[0]);
}
}
}
// 以组group的json为例,从gitlab接口获取到组的json对象
public static void main(String[] args) {
String json = "[{"id":35,"web_url":"http://worker002/groups/dpaasv2","name":"Dpaasv2","path":"dpaasv2",
"description":"DpaasV2.0的用户组","visibility":"internal","share_with_group_lock":false,
"require_two_factor_authentication":false,"two_factor_grace_period":48,
"project_creation_level":"developer","auto_devops_enabled":null,"subgroup_creation_level":"maintainer",
"emails_disabled":null,"mentions_disabled":null,"lfs_enabled":true,"default_branch_protection":2,
"avatar_url":"http://worker002/uploads/-/system/group/avatar/35/gitlab.jpg",
"request_access_enabled":true,"full_name":"Dpaasv2",
"full_path":"dpaasv2","created_at":"2020-06-08T08:14:40.647Z","parent_id":null}]";
jsonToJavaObject(json);
}
运行程序即可得到类属性,直接复制非常方便: