├── .gitignore ├── ModelGenerator.zip ├── ModelGenerator_0.4.0.zip ├── ModelGenerator_0.4.1.zip ├── ModelGenerator_0.4.2.zip ├── ModelGenerator_0.4.3.zip ├── ModelGenerator_0.4.4.zip ├── ModelGenerator_0.4.5.zip ├── img ├── 1.png ├── 2.png └── 3.png ├── lib ├── annotations-1.0.0.jar ├── com.springsource.net.sf.ezmorph-1.0.5.jar ├── com.springsource.net.sf.json-2.2.2.jar ├── com.springsource.org.apache.commons.beanutils-1.7.0.jar ├── com.springsource.org.apache.commons.collections-3.2.0.jar ├── com.springsource.org.apache.commons.lang-2.1.0.jar ├── com.springsource.org.apache.commons.logging-1.1.1.jar ├── commons-codec-1.2.jar └── commons-httpclient-3.1.jar ├── license ├── readme.en.md ├── readme.md ├── resources └── META-INF │ └── plugin.xml └── src ├── com └── moxun │ └── generator │ ├── ClassNameUtil.java │ ├── Generator.java │ ├── GeneratorEngine.java │ ├── GeneratorForm.form │ ├── GeneratorForm.java │ ├── HttpHelper.java │ ├── JSONParser.java │ ├── JSONStringInputer.form │ ├── JSONStringInputer.java │ └── Logger.java ├── fileTemplates └── internal │ └── moxun_generator_common.java.ft └── icons ├── github.png ├── icon.gif └── icon.png /.gitignore: -------------------------------------------------------------------------------- 1 | /out 2 | /.idea 3 | *.iml 4 | .DS_Store -------------------------------------------------------------------------------- /ModelGenerator.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/ModelGenerator.zip -------------------------------------------------------------------------------- /ModelGenerator_0.4.0.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/ModelGenerator_0.4.0.zip -------------------------------------------------------------------------------- /ModelGenerator_0.4.1.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/ModelGenerator_0.4.1.zip -------------------------------------------------------------------------------- /ModelGenerator_0.4.2.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/ModelGenerator_0.4.2.zip -------------------------------------------------------------------------------- /ModelGenerator_0.4.3.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/ModelGenerator_0.4.3.zip -------------------------------------------------------------------------------- /ModelGenerator_0.4.4.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/ModelGenerator_0.4.4.zip -------------------------------------------------------------------------------- /ModelGenerator_0.4.5.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/ModelGenerator_0.4.5.zip -------------------------------------------------------------------------------- /img/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/img/1.png -------------------------------------------------------------------------------- /img/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/img/2.png -------------------------------------------------------------------------------- /img/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/img/3.png -------------------------------------------------------------------------------- /lib/annotations-1.0.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/lib/annotations-1.0.0.jar -------------------------------------------------------------------------------- /lib/com.springsource.net.sf.ezmorph-1.0.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/lib/com.springsource.net.sf.ezmorph-1.0.5.jar -------------------------------------------------------------------------------- /lib/com.springsource.net.sf.json-2.2.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/lib/com.springsource.net.sf.json-2.2.2.jar -------------------------------------------------------------------------------- /lib/com.springsource.org.apache.commons.beanutils-1.7.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/lib/com.springsource.org.apache.commons.beanutils-1.7.0.jar -------------------------------------------------------------------------------- /lib/com.springsource.org.apache.commons.collections-3.2.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/lib/com.springsource.org.apache.commons.collections-3.2.0.jar -------------------------------------------------------------------------------- /lib/com.springsource.org.apache.commons.lang-2.1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/lib/com.springsource.org.apache.commons.lang-2.1.0.jar -------------------------------------------------------------------------------- /lib/com.springsource.org.apache.commons.logging-1.1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/lib/com.springsource.org.apache.commons.logging-1.1.1.jar -------------------------------------------------------------------------------- /lib/commons-codec-1.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/lib/commons-codec-1.2.jar -------------------------------------------------------------------------------- /lib/commons-httpclient-3.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/lib/commons-httpclient-3.1.jar -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 moxun 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /readme.en.md: -------------------------------------------------------------------------------- 1 | # JSON Model Generator 2 | [中文](https://github.com/misakuo/JsonModelGenerator/blob/master/readme.md) 3 | 4 | ## Introduction 5 | An code tools plugin for Intellij IDEA platform, using it to transforming JSON string to Java class. 6 | 7 | - Support get JSON String form URL; 8 | - Support field type inference; 9 | - Support generate import and implements statement, and generate implemented methods automatically; 10 | - Support parse JSONObject and JSONArray to separate class (rules: JSONObject -> Object JSONArray -> Object[] ) 11 | 12 | ## Install 13 | 1. Click [here](https://github.com/misakuo/JsonModelGenerator/raw/master/ModelGenerator.zip) to downloading file **ModelGenerator.zip** or search plugin with name **JSON Model Generator** in your IDE 14 | 2. Opening IDEA(Android Studio or others JetBrains IDE support Java can also be),open **Preferences -> Plugins -> Install plugin from disk...** select **ModelGenerator.zip** ,you can see plugin icon in toolbar after restart IDE 15 | 16 | ## Useage 17 | #### Plugin's GUI 18 | ![图1](https://raw.githubusercontent.com/misakuo/JsonModelGenerator/master/img/1.png) 19 | 20 | #### Arguments 21 | - Path:Destination of generating .java file to, set by **Select** button 22 | - URL:Plugin will fetching this URL to get JSON string, only GET method supported. sample: `http://news-at.zhihu.com/api/4/news/latest` 23 | - Author:Author's name, using in class annotation, default is current login user's name, you can set another name also. 24 | - Implements:The java interface's name it will be implemented by generated class, if you want to implement multiple interface, separate them by comma symbol. such as `Runnable,Serializable` or others interface name you defined. 25 | - Root node:Define the root node of JSONObject you want to start parsing, parsing whole JSONObject if not setting it, for example, you got JSONObject from URL is `a`, if want to parsing `a.data`, only need to setting this filed to `data` 26 | - generate sample:If selected, plugin will generating the value as annotation after filed statement in java class, for example if selected it you will got filed like `public long userId; // 27639372 ` in class 27 | 28 | **In all arguments Path、URL、Author and Package is necessary,Author and Package will be generating automatically by default. the remaining arguments could be empty if not require.** 29 | 30 | ## Todos 31 | 1. supporting generating getter and setter. 32 | 2. supporting get JSON string from user input. 33 | 3. using List replace Array. -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # JSON Model Generator 2 | [English](https://github.com/misakuo/JsonModelGenerator/blob/master/readme.en.md) 3 | 4 | ## 简介 5 | 一个 Intellij IDEA 平台插件,可以快速执行从 JSON 字符串到 Java 实体类的转换。 6 | 7 | - 支持从 URL 获取 JSON 字符串; 8 | - 支持字段值类型推断; 9 | - 支持默认 import 和默认接口实现; 10 | - 支持将类型为 JSONObject 和 JSONArray 的子元素拆分为单独的实体类; 11 | - 支持为每个字段生成getter和setter 12 | 13 | ## 安装 14 | 1. [从这里](https://github.com/misakuo/JsonModelGenerator/raw/master/ModelGenerator.zip)下载 ModelGenerator.zip 文件或在 IDE 中搜索插件 "JSON Model Generator" 15 | 2. 打开 IDEA(Android Studio或其他JetBrains系的IDE也可以),打开 Preferences -> Plugins -> Install plugin from disk... 选择 ModelGenerator.zip ,添加后重启 IDE 即可在工具栏上看到插件图标 16 | 17 | ## 使用 18 | 这个插件干了也没有什么别的,大概三件事: 19 | 20 | 1. 从 URL 获得 JSON 字符串,并解析成 JSONObject 21 | 2. 根据用户指定的根节点(如果没有指定则以整个 JSONObject 的最外层作为根节点),递归解析出每一个 Key-Value 对,推断 Value 类型并生成 Java 成员变量 22 | 3. 解析用户指定的需要实现的接口,通过反射得到方法列表、方法修饰符、返回值和参数列表,生成默认方法实现和默认返回值 23 | 24 | 如果说还有其他的就是生成默认的 package 字段(根据文件路径判断),生成默认的 import 区块,生成默认的类注释,实体类生成完之后刷新IDE的虚拟文件系统并在编辑器中打开生成的文件。但这些都是次要的,主要的就是三件事情,很惭愧,就做了一点微小的工作。 25 | 26 | ## 图解 27 | #### 插件图形界面 28 | ![图1](https://raw.githubusercontent.com/misakuo/JsonModelGenerator/master/img/1.png) 29 | 30 | #### 参数说明 31 | - Path:生成的实体类的 .java 文件存放的路径,通过右侧 Select 按钮选择 32 | - URL:可获取 JSON 字符串的 URL ,只支持 GET 请求,例如 `http://news-at.zhihu.com/api/4/news/latest` 33 | - Author:作者名称,用在类注释中,默认为当前本机登录的用户名,可自定义 34 | - package:实体类中的 package 部分,默认会根据 Path 值自动解析,如果解析错误可自定义,形如 `com.example.ui.view` 35 | - Implements:实体类中要实现的接口,例如要实现 import 字段中引入的 `com.example.inter.A` 接口,此处只需填入 `A` 即可(事实上如果在此处填入完整类路径会导致解析错误) 36 | - Root node:指定开始解析 JSONObject 的根节点,如果不填则解析整个从 URL 返回的 JSONObject ,例如从 URL 返回的 JSONObject 为 a ,而我们需要的数据位于 a 的 data 元素内,则可以在该字段内填入 `data` 37 | - generate sample:勾选此项后会在 java 实体类中将每个字段对应的返回值以注释的形式附在字段后,例如勾选了此项后生成的实体类中字段声明会是这样 `public long userId; //eg: 27639372 ` 38 | 39 | **以上参数中 Path、URL、Author 和 package 为必填参数,其中 Author 和 package 默认会自动生成。剩余三项如果不需要可以留空。** 40 | 41 | #### 示例 42 | 现在我们需要访问接口并生成一系列实体类在项目的 com.moxun.generator.gen 目录下,生成的每一个类都需要实现 com.moxun.generator.inter.A 接口 43 | 44 | 1. 点击插件图标 ![ICON](https://raw.githubusercontent.com/misakuo/JsonModelGenerator/master/src/icons/icon.gif) 启动插件 45 | 2. 填入参数如下 46 | ![图2](https://raw.githubusercontent.com/misakuo/JsonModelGenerator/master/img/2.png) 47 | 48 | 3. 点击 Generator 49 | 4. 生成成功,插件会更新 IDE 的虚拟文件系统,让 IDE 发现生成的文件并在编辑器中打开文件,生成的其中一个文件如下 50 | ![图3](https://raw.githubusercontent.com/misakuo/JsonModelGenerator/master/img/3.png) 51 | **Excited!** 52 | 53 | ## Todos 54 | - [x] 自动生成getter和setter 55 | - [x] 支持用户输入json string 56 | - [x] 使用List替代数组   57 | 58 | ## 结语 59 | 你还在对着 json 串一个个抠字段写 model 么? 不要再让变量名写错一个字母导致出现灵异错误的事情发生,快装上这个插件吧!毕竟它的 ICON 也是这么提神醒脑,蛤蛤 60 | -------------------------------------------------------------------------------- /resources/META-INF/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | com.moxun.generetor 3 | JSON Model Generator 4 | 0.5.0 5 | moxun 6 | 7 | 9 |
10 | * Support get JSON string from URL or user's input.
11 | * Support data conversion library like fastjson.
12 | * Support auto implementation Java interface.
13 | * Support generate getter and setter.
14 | * Support field type inference.

15 | Sourcecode and Tutorial
16 | Bug report
17 |
Hope you enjoy it :)

18 | 19 | ]]>
20 | 21 | 0.5.0
23 | Support generate getter and setter;
24 | 0.4.5
25 | Modify value type inference rules;
26 | 0.4.4
27 | Better support for value type inference;
28 | 0.4.3
29 | You can specified the name of root class now (default is the directory's name);
30 | 0.4.2
31 | Replaced with a new icon;
32 | Support parsing JSON Array to List;
33 | 0.4.1
34 | Fixed conflicts of the same name parameter elements,you can using this case to testing;
35 | 0.4.0
36 | Fixed crash in Android Studio 2.0 Preview;
37 | You can specify the source of JSON string by URL or user input now;
38 | Parsing JSONArray as root node is supported, plugin will traverse the whole array and finding the first JSONObject child to start parsing.
39 | 0.3.1
40 | Building plugin with Java 6, you can using it with JDK1.6 and higher;
41 | Bug Fixed, some new feature added.
42 | 0.3.0
43 | Async file writing, fix ClassNotFoundException when class not in classpath, more rubust.
44 | 0.2.1
45 | Add logger, support show log to Event Log.
46 | 0.2.0
47 | Handle all exception occurred on plugin.
48 | 0.1.0
49 | Created.
50 | ]]> 51 |
52 | 53 | 54 | 55 | 56 | 58 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 79 | 80 | 81 | 82 | 83 | 84 |
-------------------------------------------------------------------------------- /src/com/moxun/generator/ClassNameUtil.java: -------------------------------------------------------------------------------- 1 | package com.moxun.generator; 2 | 3 | /** 4 | * Created by moxun on 16/3/7. 5 | */ 6 | public class ClassNameUtil { 7 | public static String getName(String name) { 8 | char[] chars = name.toCharArray(); 9 | for (int i = 0; i < chars.length; i++) { 10 | char c = chars[i]; 11 | if (!Character.isLetter(c)) { 12 | chars[i] = '_'; 13 | if (i + 1 < chars.length) { 14 | chars[i + 1] = Character.toUpperCase(chars[i + 1]); 15 | } 16 | } 17 | } 18 | 19 | return String.valueOf(chars).replaceAll("_",""); 20 | } 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/com/moxun/generator/Generator.java: -------------------------------------------------------------------------------- 1 | package com.moxun.generator; 2 | 3 | import com.intellij.openapi.actionSystem.AnAction; 4 | import com.intellij.openapi.actionSystem.AnActionEvent; 5 | import com.intellij.openapi.project.Project; 6 | 7 | /** 8 | * 插件入口 9 | * Created by moxun on 15/11/26. 10 | */ 11 | public class Generator extends AnAction{ 12 | @Override 13 | public void actionPerformed(AnActionEvent anActionEvent) { 14 | Project project = anActionEvent.getProject(); 15 | Logger.init(); 16 | GeneratorForm form = new GeneratorForm(project); 17 | form.show(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/com/moxun/generator/GeneratorEngine.java: -------------------------------------------------------------------------------- 1 | package com.moxun.generator; 2 | 3 | import com.intellij.codeInsight.generation.GenerateMembersUtil; 4 | import com.intellij.openapi.application.ApplicationManager; 5 | import com.intellij.openapi.application.Result; 6 | import com.intellij.openapi.command.WriteCommandAction; 7 | import com.intellij.openapi.project.Project; 8 | import com.intellij.psi.*; 9 | import com.intellij.psi.search.GlobalSearchScope; 10 | import com.intellij.psi.search.PsiShortNamesCache; 11 | import org.jetbrains.annotations.NotNull; 12 | 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | /** 17 | * Generating code 18 | * Created by moxun on 15/12/9. 19 | */ 20 | public class GeneratorEngine { 21 | private Map dataSet = new HashMap(); 22 | private Project project; 23 | private PsiDirectory directory; 24 | private PsiElementFactory factory; 25 | private String pkgName; 26 | private String[] inters; 27 | private boolean genGetter; 28 | private boolean genSetter; 29 | 30 | public GeneratorEngine(Project proj, PsiDirectory dir) { 31 | dataSet.clear(); 32 | project = proj; 33 | directory = dir; 34 | factory = JavaPsiFacade.getInstance(project).getElementFactory(); 35 | } 36 | 37 | public void init(String pkg, String[] its) { 38 | pkgName = pkg; 39 | if (its != null) { 40 | inters = its.clone(); 41 | } 42 | } 43 | 44 | public void append(final String s, final String clsName) { 45 | ApplicationManager.getApplication().invokeLater(new Runnable() { 46 | @Override 47 | public void run() { 48 | new WriteCommandAction(project) { 49 | @Override 50 | protected void run(@NotNull Result result) throws Throwable { 51 | PsiClass dist = dataSet.get(clsName); 52 | if (s.startsWith("//")) { 53 | PsiElement comment = factory.createCommentFromText(s, dist); 54 | dist.addBefore(comment, dist.getRBrace()); 55 | } else { 56 | String r = s.replaceAll("-", "_"); 57 | PsiField field = factory.createFieldFromText(r, dist); 58 | dist.add(field); 59 | if (genGetter) { 60 | PsiMethod getter = GenerateMembersUtil.generateGetterPrototype(field); 61 | dist.add(getter); 62 | } 63 | if (genSetter) { 64 | PsiMethod setter = GenerateMembersUtil.generateSetterPrototype(field); 65 | dist.add(setter); 66 | } 67 | } 68 | 69 | if (s.contains("public List<")) { 70 | PsiImportStatement[] imports = ((PsiJavaFile) dist.getContainingFile()).getImportList().getImportStatements(); 71 | if (imports != null) { 72 | boolean isAdded = false; 73 | for (PsiImportStatement importStatement : imports) { 74 | if (importStatement.getQualifiedName().equals("java.util.List")) { 75 | isAdded = true; 76 | } 77 | } 78 | if (!isAdded) { 79 | GlobalSearchScope searchScope = GlobalSearchScope.allScope(project); 80 | PsiClass[] psiClasses = PsiShortNamesCache.getInstance(project).getClassesByName("List", searchScope); 81 | for (PsiClass psiClass : psiClasses) { 82 | if (psiClass.getQualifiedName().equals("java.util.List")) { 83 | PsiImportStatement importStatement = factory.createImportStatement(psiClass); 84 | ((PsiJavaFile) dist.getContainingFile()).getImportList().add(importStatement); 85 | break; 86 | } 87 | } 88 | } 89 | } else { 90 | GlobalSearchScope searchScope = GlobalSearchScope.allScope(project); 91 | PsiClass[] psiClasses = PsiShortNamesCache.getInstance(project).getClassesByName("List", searchScope); 92 | for (PsiClass psiClass : psiClasses) { 93 | if (psiClass.getQualifiedName().equals("java.util.List")) { 94 | PsiImportStatement importStatement = factory.createImportStatement(psiClass); 95 | ((PsiJavaFile) dist.getContainingFile()).getImportList().add(importStatement); 96 | break; 97 | } 98 | } 99 | } 100 | } 101 | } 102 | }.execute(); 103 | } 104 | }); 105 | } 106 | 107 | public String preGen(String name, String last) { 108 | String className = name; 109 | final PsiFile psiFile = directory.findFile(name + ".java"); 110 | String clazzName = name; 111 | if (psiFile != null) { 112 | clazzName = last + name; 113 | Logger.warn("File [" + name + ".java" + "] already exists, assign [" + clazzName + "] to current class."); 114 | if (directory.findFile(clazzName + ".java") != null) { 115 | for (int i = 1; i <= 50; i++) { 116 | if (directory.findFile(clazzName + i + ".java") == null) { 117 | Logger.warn("File [" + clazzName + ".java" + "] already exists, assign [" + clazzName + i + "] to current class."); 118 | clazzName = clazzName + i; 119 | className = clazzName; 120 | break; 121 | } 122 | } 123 | } 124 | } 125 | 126 | final PsiClass clazz = JavaDirectoryService.getInstance().createClass(directory, clazzName, "moxun_generator_common"); 127 | dataSet.put(name, clazz); 128 | GlobalSearchScope searchScope = GlobalSearchScope.allScope(project); 129 | if (inters != null) { 130 | for (String inter : inters) { 131 | PsiClass[] psiClasses = PsiShortNamesCache.getInstance(project).getClassesByName(inter, searchScope); 132 | if (psiClasses.length > 0) { 133 | final PsiJavaCodeReferenceElement ref = factory.createClassReferenceElement(psiClasses[0]); 134 | final PsiMethod[] methods = psiClasses[0].getAllMethods(); 135 | ApplicationManager.getApplication().invokeLater(new Runnable() { 136 | @Override 137 | public void run() { 138 | new WriteCommandAction(project) { 139 | @Override 140 | protected void run(@NotNull Result result) throws Throwable { 141 | clazz.getImplementsList().add(ref); 142 | ((PsiJavaFile) clazz.getContainingFile()).setPackageName(pkgName); 143 | for (PsiMethod m : methods) { 144 | if (m.getModifierList().hasModifierProperty("abstract")) { 145 | PsiMethod psiMethod = null; 146 | try { 147 | psiMethod = factory.createMethod(m.getName(), m.getReturnType()); 148 | for (PsiElement param : m.getParameterList().getParameters()) { 149 | psiMethod.getParameterList().add(param); 150 | } 151 | if (getReturnStatement(m.getReturnType()) != null) { 152 | PsiStatement statement = factory.createStatementFromText("return " + getReturnStatement(m.getReturnType()) + ";\n", psiMethod); 153 | psiMethod.getBody().add(statement); 154 | } 155 | psiMethod.getModifierList().addAnnotation("Override"); 156 | } catch (NullPointerException npe) { 157 | //do nothing 158 | Logger.error("NPE: " + npe.toString()); 159 | } 160 | if (psiMethod != null) { 161 | clazz.add(psiMethod); 162 | } 163 | } 164 | } 165 | } 166 | }.execute(); 167 | } 168 | }); 169 | } else { 170 | Logger.warn("Java interface [" + inter + "] not found in this project."); 171 | } 172 | } 173 | } 174 | return className; 175 | } 176 | 177 | private String getReturnStatement(PsiType type) { 178 | if (type.equalsToText("void")) { 179 | return null; 180 | } else if (type.equalsToText("boolean")) { 181 | return "false"; 182 | } else if (type.equalsToText("short") || type.equalsToText("byte") || type.equalsToText("int") 183 | || type.equalsToText("long") || type.equalsToText("float") || type.equalsToText("double")) { 184 | return "0"; 185 | } else { 186 | return "null"; 187 | } 188 | } 189 | 190 | void setGenGetter(boolean genGetter) { 191 | this.genGetter = genGetter; 192 | } 193 | 194 | void setGenSetter(boolean genSetter) { 195 | this.genSetter = genSetter; 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/com/moxun/generator/GeneratorForm.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | -------------------------------------------------------------------------------- /src/com/moxun/generator/GeneratorForm.java: -------------------------------------------------------------------------------- 1 | package com.moxun.generator; 2 | 3 | import com.intellij.openapi.fileChooser.FileChooser; 4 | import com.intellij.openapi.fileChooser.FileChooserDescriptor; 5 | import com.intellij.openapi.fileEditor.FileEditorManager; 6 | import com.intellij.openapi.fileEditor.OpenFileDescriptor; 7 | import com.intellij.openapi.project.Project; 8 | import com.intellij.openapi.ui.Messages; 9 | import com.intellij.openapi.vfs.LocalFileSystem; 10 | import com.intellij.openapi.vfs.VirtualFile; 11 | import com.intellij.openapi.wm.WindowManager; 12 | import com.intellij.psi.PsiDirectory; 13 | import com.intellij.psi.impl.file.PsiDirectoryFactory; 14 | import net.sf.json.JSONArray; 15 | import net.sf.json.JSONException; 16 | import net.sf.json.JSONObject; 17 | 18 | import javax.swing.*; 19 | import java.awt.*; 20 | import java.awt.event.*; 21 | import java.io.File; 22 | import java.io.IOException; 23 | import java.net.URI; 24 | import java.net.URISyntaxException; 25 | import java.util.ArrayList; 26 | import java.util.List; 27 | 28 | /** 29 | * 生成器窗体 30 | * Created by moxun on 15/11/26. 31 | */ 32 | public class GeneratorForm { 33 | private JTextField authorText; 34 | private JTextField implementsText; 35 | private JTextField rootText; 36 | private JCheckBox generatorSampleCheckBox; 37 | private JButton generatorButton; 38 | private JTextField dirPath; 39 | private JButton selectButton; 40 | private JTextField urlText; 41 | private JTextField pkgText; 42 | private JPanel panel; 43 | private JButton gitButton; 44 | private JComboBox source; 45 | private JRadioButton arrayRadioButton; 46 | private JRadioButton listERadioButton; 47 | private JLabel status; 48 | private JTextField rootName; 49 | private JCheckBox generateGetterCheckBox; 50 | private JCheckBox generateSetterCheckBox; 51 | 52 | private Project project; 53 | private List textFields = new ArrayList(); 54 | private String mainClassName, basePath; 55 | private String[] implement; 56 | 57 | private JFrame frame; 58 | 59 | private JSONParser parser; 60 | 61 | private String jsonString; 62 | 63 | 64 | public GeneratorForm(Project p_project) { 65 | project = p_project; 66 | textFields.clear(); 67 | textFields.add(authorText); 68 | textFields.add(dirPath); 69 | textFields.add(urlText); 70 | textFields.add(pkgText); 71 | 72 | ButtonGroup group = new ButtonGroup(); 73 | group.add(arrayRadioButton); 74 | group.add(listERadioButton); 75 | 76 | parser = new JSONParser(); 77 | } 78 | 79 | public void show() { 80 | setListener(); 81 | authorText.setText(System.getProperty("user.name")); 82 | frame = new JFrame("JSON Model Generator"); 83 | frame.setContentPane(panel); 84 | frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 85 | frame.pack(); 86 | frame.setLocationRelativeTo(frame.getParent()); 87 | frame.setVisible(true); 88 | } 89 | 90 | private void setListener() { 91 | for (final JTextField textField : textFields) { 92 | textField.addFocusListener(new FocusListener() { 93 | @Override 94 | public void focusGained(FocusEvent e) { 95 | textField.setBackground(Color.YELLOW); 96 | } 97 | 98 | @Override 99 | public void focusLost(FocusEvent e) { 100 | textField.setBackground(Color.WHITE); 101 | } 102 | }); 103 | } 104 | 105 | urlText.addMouseListener(new MouseAdapter() { 106 | @Override 107 | public void mouseClicked(MouseEvent e) { 108 | if (source.getSelectedIndex() == 1) { 109 | showInputer(); 110 | } 111 | } 112 | }); 113 | 114 | source.addActionListener(new ActionListener() { 115 | @Override 116 | public void actionPerformed(ActionEvent e) { 117 | if (source.getSelectedItem().toString().equals("Input")) { 118 | showInputer(); 119 | } else { 120 | urlText.setEditable(true); 121 | urlText.setText(""); 122 | } 123 | } 124 | }); 125 | 126 | selectButton.addActionListener(new ActionListener() { 127 | @Override 128 | public void actionPerformed(ActionEvent e) { 129 | frame.setVisible(false); 130 | showFileChoicer(); 131 | } 132 | }); 133 | generatorButton.addActionListener(new ActionListener() { 134 | @Override 135 | public void actionPerformed(ActionEvent e) { 136 | status.setText("Start generating……"); 137 | status.paintImmediately(status.getBounds()); 138 | if (check()) { 139 | if (rootName.getText() != null && rootName.getText().length() > 0) { 140 | mainClassName = rootName.getText(); 141 | } 142 | 143 | JSONObject response; 144 | if (source.getSelectedIndex() == 0) { 145 | status.setText("Start fetching URL……"); 146 | status.paintImmediately(status.getBounds()); 147 | response = parseString(HttpHelper.getResponse(urlText.getText())); 148 | status.setText("Fetch URL complete."); 149 | status.paintImmediately(status.getBounds()); 150 | } else { 151 | response = parseString(jsonString); 152 | } 153 | JSONObject dist = null; 154 | 155 | if (response == null) { 156 | Messages.showErrorDialog(project, "Parsing JSON failed, see detail on Event Log", "Error"); 157 | return; 158 | } 159 | 160 | if (!rootText.getText().isEmpty() && response != null) { 161 | dist = response.getJSONObject(rootText.getText()); 162 | } 163 | 164 | if (dist == null) { 165 | dist = response; 166 | } 167 | 168 | processImplements(); 169 | 170 | status.setText("Start parsing JSON……"); 171 | status.paintImmediately(status.getBounds()); 172 | 173 | parser.init(mainClassName, pkgText.getText(), implement, listERadioButton.isSelected()); 174 | parser.setGenSample(generatorSampleCheckBox.isSelected()); 175 | parser.setGenGetter(generateGetterCheckBox.isSelected()); 176 | parser.setGenSetter(generateSetterCheckBox.isSelected()); 177 | String className = parser.decodeJSONObject(dist); 178 | 179 | status.setText("Generating complete."); 180 | status.paintImmediately(status.getBounds()); 181 | 182 | Messages.showInfoMessage(project, "Generating success!", "Success"); 183 | frame.dispose(); 184 | File file = new File(basePath + className + ".java"); 185 | if (file.exists()) { 186 | VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); 187 | if (virtualFile != null) { 188 | virtualFile.refresh(false, true); 189 | FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, virtualFile), true); 190 | } 191 | } 192 | } 193 | } 194 | }); 195 | 196 | gitButton.addActionListener(new ActionListener() { 197 | @Override 198 | public void actionPerformed(ActionEvent e) { 199 | try { 200 | URI uri = new URI("https://github.com/misakuo/JsonModelGenerator"); 201 | Desktop.getDesktop().browse(uri); 202 | } catch (URISyntaxException e1) { 203 | e1.printStackTrace(); 204 | } catch (IOException e1) { 205 | e1.printStackTrace(); 206 | } 207 | } 208 | }); 209 | } 210 | 211 | private void showInputer() { 212 | frame.setAlwaysOnTop(false); 213 | new JSONStringInputer(new JSONStringInputer.CommitCallback() { 214 | @Override 215 | public void onCommit(String src) { 216 | jsonString = src; 217 | String snapshot; 218 | if (src.length() > 10) { 219 | snapshot = src.substring(0, 10); 220 | } else { 221 | snapshot = src; 222 | } 223 | urlText.setText("[JSONString from user input] " + snapshot + " ……"); 224 | urlText.setEditable(false); 225 | frame.setAlwaysOnTop(true); 226 | } 227 | }).show(); 228 | } 229 | 230 | private JSONObject parseString(String src) { 231 | if (src != null) { 232 | if (src.startsWith("{")) { 233 | JSONObject ret = null; 234 | try { 235 | ret = JSONObject.fromObject(src); 236 | } catch (JSONException e) { 237 | Logger.error(e.getMessage()); 238 | } 239 | return ret; 240 | } else if (src.startsWith("[")) { 241 | JSONArray ret = null; 242 | try { 243 | ret = JSONArray.fromObject(src); 244 | for (Object obj : ret) { 245 | if (obj instanceof JSONObject) { 246 | return (JSONObject) obj; 247 | } 248 | } 249 | Logger.error("No JSONObject found on this JSONArray"); 250 | return null; 251 | } catch (JSONException e) { 252 | Logger.error(e.getMessage()); 253 | } 254 | return null; 255 | } else { 256 | if (src.length() > 50) { 257 | src = src.substring(0, 50); 258 | } 259 | Logger.error(new StringBuilder().append("Parse failed, it maybe not a json string : ").append(src) 260 | .append(" (").append(src.length()).append(" characters more) ……").toString()); 261 | return null; 262 | } 263 | } else { 264 | Logger.error("Input string is null"); 265 | return null; 266 | } 267 | } 268 | 269 | private void showFileChoicer() { 270 | FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false); 271 | VirtualFile virtualFile = FileChooser.chooseFile(descriptor, WindowManager.getInstance().findVisibleFrame(), project, null); 272 | if (virtualFile != null) { 273 | PsiDirectory directory = PsiDirectoryFactory.getInstance(project).createDirectory(virtualFile); 274 | mainClassName = directory.getName(); 275 | 276 | char[] chars = mainClassName.toCharArray(); 277 | chars[0] = Character.toUpperCase(chars[0]); 278 | rootName.setText(String.valueOf(chars)); 279 | 280 | parser.reset(project, directory); 281 | String path = virtualFile.getPath(); 282 | String pkg = ""; 283 | dirPath.setText(path); 284 | if (path.contains("java")) { 285 | pkg = path.split("java/")[1].replaceAll("/", "."); 286 | } else if (path.contains("src")) { 287 | pkg = path.split("src/")[1].replaceAll("/", "."); 288 | } 289 | basePath = path + "/"; 290 | pkgText.setText(pkg); 291 | 292 | Logger.info("Target path " + path); 293 | } else { 294 | Logger.warn("Empty target path!"); 295 | } 296 | frame.setAlwaysOnTop(true); 297 | frame.setVisible(true); 298 | } 299 | 300 | private boolean check() { 301 | boolean pass = true; 302 | for (JTextField textField : textFields) { 303 | if (textField.getText().isEmpty()) { 304 | textField.setBackground(new Color(0xff, 0xae, 0xb9)); 305 | pass = false; 306 | } else { 307 | textField.setBackground(new Color(0xff, 0xff, 0xff)); 308 | } 309 | } 310 | return pass; 311 | } 312 | 313 | private void processImplements() { 314 | String implementsTxt = implementsText.getText(); 315 | 316 | if (!implementsTxt.isEmpty()) { 317 | implement = implementsText.getText().split(","); 318 | } 319 | } 320 | } 321 | -------------------------------------------------------------------------------- /src/com/moxun/generator/HttpHelper.java: -------------------------------------------------------------------------------- 1 | package com.moxun.generator; 2 | 3 | import net.sf.json.JSONObject; 4 | import org.apache.commons.httpclient.HttpClient; 5 | import org.apache.commons.httpclient.methods.GetMethod; 6 | 7 | import java.io.IOException; 8 | 9 | /** 10 | * Tool to access URL 11 | * Created by moxun on 15/11/26. 12 | */ 13 | public class HttpHelper { 14 | public static String getResponse(String url) { 15 | String data = null; 16 | try { 17 | HttpClient httpClient = new HttpClient(); 18 | GetMethod httpGet = new GetMethod(url); 19 | int code = httpClient.executeMethod(httpGet); 20 | 21 | if (code == 200) { 22 | data = httpGet.getResponseBodyAsString(); 23 | httpGet.releaseConnection(); 24 | return data; 25 | } else { 26 | Logger.error("HTTP GET return " + code); 27 | return null; 28 | } 29 | } catch (IOException e) { 30 | Logger.error(e.getMessage()); 31 | } 32 | return null; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/moxun/generator/JSONParser.java: -------------------------------------------------------------------------------- 1 | package com.moxun.generator; 2 | 3 | import com.intellij.openapi.project.Project; 4 | import com.intellij.psi.PsiDirectory; 5 | import net.sf.json.JSONArray; 6 | import net.sf.json.JSONObject; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Iterator; 10 | import java.util.List; 11 | import java.util.Stack; 12 | import java.util.regex.Pattern; 13 | 14 | /** 15 | * Parsing json and generating code 16 | * Created by moxun on 15/12/9. 17 | */ 18 | public class JSONParser { 19 | private Stack path = new Stack(); 20 | private List allNodes = new ArrayList(); 21 | private boolean needGenSample = false; 22 | private GeneratorEngine engine; 23 | private boolean isArrayToList = false; 24 | private boolean genGetter; 25 | private boolean genSetter; 26 | 27 | public void reset(Project proj, PsiDirectory dir) { 28 | path.clear(); 29 | allNodes.clear(); 30 | engine = new GeneratorEngine(proj, dir); 31 | } 32 | 33 | public void init(String mainClassName, String pkg, String[] its, boolean isArrayToList) { 34 | push(suffixToUppercase(mainClassName)); 35 | engine.init(pkg, its); 36 | this.isArrayToList = isArrayToList; 37 | } 38 | 39 | public void setGenSample(boolean has) { 40 | needGenSample = has; 41 | } 42 | 43 | public String decodeJSONObject(JSONObject json) { 44 | String className = null; 45 | Iterator keys = json.keys(); 46 | JSONObject current = null; 47 | Object value; 48 | String key; 49 | String last = ""; 50 | if (path.size() > 1) { 51 | last = path.get(path.size() - 2); 52 | } 53 | className = engine.preGen(path.peek(), last); 54 | while (keys.hasNext()) { 55 | key = keys.next(); 56 | value = json.get(key); 57 | key = ClassNameUtil.getName(key); 58 | if (value instanceof JSONObject) { 59 | String validName = ClassNameUtil.getName(suffixToUppercase(key)); 60 | String modifier = getModifier(); 61 | append(modifier + validName + " " + key + ";\n"); 62 | push(validName); 63 | current = (JSONObject) value; 64 | if (current.keySet().size() > 0) { 65 | decodeJSONObject(current); 66 | } else { 67 | String last1 = ""; 68 | if (path.size() > 1) { 69 | last1 = path.get(path.size() - 2); 70 | } 71 | engine.preGen(path.peek(), last1); 72 | append("// TODO: complemented needed maybe."); 73 | Logger.warn("Success to generating file " + path.peek() + ".java but it have no field"); 74 | path.pop(); 75 | } 76 | } else if (value instanceof JSONArray) { 77 | JSONArray v = (JSONArray) value; 78 | if (v.size() > 0 && !(v.get(0) instanceof JSONObject)) { 79 | Object firstValue = v.get(0); 80 | //处理基本数据类型数组和String数组 81 | String field = getModifier() + getArrayType(decisionValueType(key, firstValue, true), isArrayToList) + " " + key + ";\n"; 82 | append(field); 83 | } else { 84 | //处理对象数组 85 | if (isArrayToList) { 86 | append(getModifier() + "List<" + suffixToUppercase(key) + "Item>" + key + ";\n"); 87 | } else { 88 | append(getModifier() + suffixToUppercase(key) + "Item[] " + key + ";\n"); 89 | } 90 | } 91 | push(suffixToUppercase(key)); 92 | decodeJSONArray((JSONArray) value); 93 | } else { 94 | //处理基本数据类型和String 95 | String field = getModifier(); 96 | field += decisionValueType(key, value, false) + " " + key + ";"; 97 | if (needGenSample) { 98 | String v = String.valueOf(value); 99 | v = v.replaceAll("\n", ""); 100 | if (v.length() > 15) { 101 | v = v.substring(0, 15); 102 | } 103 | field = field + "\t// " + v; 104 | } 105 | append(field); 106 | } 107 | } 108 | 109 | Logger.info("Success to generating file " + path.peek() + ".java"); 110 | if (!path.isEmpty()) { 111 | path.pop(); 112 | } 113 | return className; 114 | } 115 | 116 | private String getModifier() { 117 | if (!genGetter && !genSetter) { 118 | return "public "; 119 | } else { 120 | return "private "; 121 | } 122 | } 123 | 124 | private String decisionValueType(/*not uesd*/String key, Object value, boolean formArray) { 125 | if (formArray) { 126 | return value.getClass().getSimpleName(); 127 | } else { 128 | if (value instanceof Integer) { 129 | return "int"; 130 | } else if (value instanceof Long) { 131 | return "long"; 132 | } else if (value instanceof Double) { 133 | return "double"; 134 | } else if (value instanceof Boolean) { 135 | return "boolean"; 136 | } 137 | } 138 | return "String"; 139 | } 140 | 141 | @Deprecated 142 | private String __inferValueType(String key, String value, boolean formArray) { 143 | String type = "String"; 144 | if (isNumeric(value)) { 145 | if (isInteger(value)) { 146 | if (value.length() > 8 || key.contains("Id") || key.contains("id") || key.contains("ID")) { 147 | if (formArray) { 148 | return "Long"; 149 | } 150 | return "long"; 151 | } else { 152 | if (formArray) { 153 | return "Integer"; 154 | } 155 | return "int"; 156 | } 157 | } else { 158 | String[] tmp = value.split("\\."); 159 | int fLength = 0; 160 | if (tmp.length > 1) { 161 | fLength = value.split("\\.")[1].length(); 162 | } else { 163 | Logger.error(value); 164 | } 165 | 166 | if (fLength > 8) { 167 | if (formArray) { 168 | return "Double"; 169 | } else { 170 | return "double"; 171 | } 172 | } else { 173 | if (formArray) { 174 | return "Float"; 175 | } else { 176 | return "float"; 177 | } 178 | } 179 | } 180 | } else if (value.equals("true") || value.equals("false")) { 181 | if (formArray) { 182 | return "Boolean"; 183 | } else { 184 | return "boolean"; 185 | } 186 | } 187 | return type; 188 | } 189 | 190 | private String getArrayType(String baseType, boolean isArrayToList) { 191 | if (isArrayToList) { 192 | return "List<" + baseType + ">"; 193 | } else { 194 | return baseType + "[]"; 195 | } 196 | } 197 | 198 | public void decodeJSONArray(JSONArray jsonArray) { 199 | 200 | // //是否需要遍历? 201 | // for (item in jsonArray) { 202 | // if (item instanceof JSONObject) { 203 | // push(path.peek() + "Item") 204 | // decodeJSONObject(item) 205 | // } else if (item instanceof JSONArray) { 206 | // push("array" + index + "->") 207 | // decodeJSONArray(item) 208 | // } else { 209 | // 210 | // } 211 | // } 212 | 213 | //数组选择其中一个元素出来进行解析就OK 214 | Object item = jsonArray.get(0); 215 | if (item instanceof JSONObject) { 216 | push(path.peek() + "Item"); 217 | decodeJSONObject((JSONObject) item); 218 | } else if (item instanceof JSONArray) { 219 | //多维数组我选择狗带 220 | push(path.peek() + "Item"); 221 | decodeJSONArray((JSONArray) item); 222 | } else { 223 | 224 | } 225 | 226 | if (!path.isEmpty()) { 227 | path.pop(); 228 | } 229 | } 230 | 231 | public String suffixToUppercase(String s) { 232 | StringBuilder sb = new StringBuilder(s); 233 | sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); 234 | return sb.toString(); 235 | } 236 | 237 | //正负整数,浮点数 238 | public boolean isNumeric(String str) { 239 | Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*"); 240 | return pattern.matcher(str).matches(); 241 | } 242 | 243 | private boolean isInteger(String str) { 244 | Pattern pattern = Pattern.compile("-?[0-9]+"); 245 | return pattern.matcher(str).matches(); 246 | } 247 | 248 | public void append(String field) { 249 | engine.append(field, path.peek()); 250 | } 251 | 252 | private void push(String name) { 253 | String uniqueName = ClassNameUtil.getName(name); 254 | if (allNodes.contains(name)) { 255 | uniqueName = path.peek() + name; 256 | } 257 | 258 | if (allNodes.contains(uniqueName)) { 259 | for (int i = 1; i <= 50; i++) { 260 | uniqueName = uniqueName + i; 261 | if (!allNodes.contains(uniqueName)) { 262 | break; 263 | } 264 | } 265 | } 266 | 267 | allNodes.add(uniqueName); 268 | path.push(uniqueName); 269 | } 270 | 271 | void setGenGetter(boolean genGetter) { 272 | this.genGetter = genGetter; 273 | engine.setGenGetter(genGetter); 274 | } 275 | 276 | void setGenSetter(boolean genSetter) { 277 | this.genSetter = genSetter; 278 | engine.setGenSetter(genSetter); 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /src/com/moxun/generator/JSONStringInputer.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 |
46 | -------------------------------------------------------------------------------- /src/com/moxun/generator/JSONStringInputer.java: -------------------------------------------------------------------------------- 1 | package com.moxun.generator; 2 | 3 | import net.sf.json.JSONArray; 4 | import net.sf.json.JSONException; 5 | import net.sf.json.JSONObject; 6 | 7 | import javax.swing.*; 8 | import java.awt.event.ActionEvent; 9 | import java.awt.event.ActionListener; 10 | import java.util.regex.Matcher; 11 | import java.util.regex.Pattern; 12 | 13 | /** 14 | * Frame to allow user input string and checking it is JSON or not 15 | * Created by moxun on 16/1/23. 16 | */ 17 | public class JSONStringInputer { 18 | private JTextArea textArea1; 19 | private JPanel panel1; 20 | private JButton commitButton; 21 | private JLabel status; 22 | private CommitCallback commitCallback; 23 | private JFrame frame; 24 | 25 | public JSONStringInputer(CommitCallback callback) { 26 | init(); 27 | commitCallback = callback; 28 | } 29 | 30 | private void init() { 31 | textArea1.setLineWrap(true); 32 | textArea1.setWrapStyleWord(true); 33 | 34 | commitButton.addActionListener(new ActionListener() { 35 | @Override 36 | public void actionPerformed(ActionEvent e) { 37 | String text = textArea1.getText(); 38 | String src = replaceBlank(text); 39 | if (src.startsWith("{")) { 40 | try { 41 | JSONObject jsonObject = JSONObject.fromObject(src); 42 | status.setVisible(false); 43 | commitCallback.onCommit(src); 44 | frame.dispose(); 45 | } catch (JSONException ex) { 46 | status.setVisible(true); 47 | status.setText("Exception:" + ex.getMessage()); 48 | } 49 | } else if (src.startsWith("[")) { 50 | try { 51 | JSONArray jsonArray = JSONArray.fromObject(src); 52 | status.setVisible(false); 53 | commitCallback.onCommit(src); 54 | frame.dispose(); 55 | } catch (JSONException ex) { 56 | status.setVisible(true); 57 | status.setText("Exception:" + ex.getMessage()); 58 | } 59 | } else { 60 | status.setText("Can't formatting input content to JSON"); 61 | status.setVisible(true); 62 | } 63 | } 64 | }); 65 | } 66 | 67 | public String replaceBlank(String str) { 68 | String dest = ""; 69 | if (str!=null) { 70 | Pattern p = Pattern.compile("\\s*|\t|\r|\n"); 71 | Matcher m = p.matcher(str); 72 | dest = m.replaceAll(""); 73 | } 74 | return dest; 75 | } 76 | 77 | public void show() { 78 | frame = new JFrame("Input your JSON string"); 79 | frame.setContentPane(panel1); 80 | frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 81 | frame.setLocationRelativeTo(frame.getParent()); 82 | frame.pack(); 83 | frame.setVisible(true); 84 | frame.setAlwaysOnTop(true); 85 | } 86 | 87 | public interface CommitCallback { 88 | void onCommit(String src); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/com/moxun/generator/Logger.java: -------------------------------------------------------------------------------- 1 | package com.moxun.generator; 2 | 3 | import com.intellij.notification.*; 4 | 5 | /** 6 | * logger 7 | * Created by moxun on 15/11/27. 8 | */ 9 | public class Logger { 10 | public static void init() { 11 | NotificationsConfiguration.getNotificationsConfiguration().register("JSON Model Generator", NotificationDisplayType.NONE); 12 | } 13 | 14 | public static void info(String text) { 15 | Notifications.Bus.notify( 16 | new Notification("JSON Model Generator","JSON Model Generator [INFO]",text, NotificationType.INFORMATION)); 17 | } 18 | 19 | public static void warn(String text) { 20 | Notifications.Bus.notify( 21 | new Notification("JSON Model Generator","JSON Model Generator [WARNING]",text, NotificationType.WARNING)); 22 | } 23 | 24 | public static void error(String text) { 25 | Notifications.Bus.notify( 26 | new Notification("JSON Model Generator","JSON Model Generator [ERROR]",text, NotificationType.ERROR)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/fileTemplates/internal/moxun_generator_common.java.ft: -------------------------------------------------------------------------------- 1 | #if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end 2 | 3 | /** 4 | * Author: ${USER} 5 | * Created by: ModelGenerator on ${DATE} 6 | */ 7 | public class ${NAME} { 8 | } -------------------------------------------------------------------------------- /src/icons/github.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/src/icons/github.png -------------------------------------------------------------------------------- /src/icons/icon.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/src/icons/icon.gif -------------------------------------------------------------------------------- /src/icons/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/misakuo/JsonModelGenerator/8651f58535c94f09dce650ec039dab58de7dcf56/src/icons/icon.png --------------------------------------------------------------------------------