json一键生成javabean

简介

简介:指定json数据接口地址,指定包名和类名,即可在控制台输出工具类,有兴趣的童鞋可以继续扩展。

代码

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
304
305
306
307
308
309
310
311
312
package info.enjoycode.tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;
import java.util.Map.Entry;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;

/**
* json解析工具类
*
* @author Administrator
*
*/

public class JsonGenerator {
static String packageName = "info.enjoycode.bean";

public static void main(String[] args) throws UnsupportedEncodingException,
IOException {

// json接口地址
String urlStr = "http://enjoycode.info/uploads/test.json";
// 类名
String entityName = "DemoEntity";
String jsonStr = getJsonFromNet(urlStr);

JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(jsonStr);
// 创建最外层的类
SubClass mainClass = new SubClass(entityName);
// 解析jsonElement
parseJsonElement(mainClass, entityName, jsonElement);

System.out.println(generateWholeClass(mainClass));

}

/**
* 联网获取json
*
* @param urlStr
* @return
* @throws MalformedURLException
* @throws IOException
*/

private static String getJsonFromNet(String urlStr)
throws MalformedURLException, IOException {

URL url = new URL(urlStr);
URLConnection connection = url.openConnection();

connection.setDoOutput(true);
String sCurrentLine;
String sTotalString;
sCurrentLine = "";
sTotalString = "";
InputStream l_urlStream;
l_urlStream = connection.getInputStream();
// 传说中的三层包装阿!
BufferedReader l_reader = new BufferedReader(new InputStreamReader(
l_urlStream));
while ((sCurrentLine = l_reader.readLine()) != null) {
sTotalString += sCurrentLine;
}
return sTotalString;
}

private static String generateWholeClass(SubClass clazz) {
String initialTabStr = getInitialTabStr(clazz);
StringBuffer sb = new StringBuffer();
if (clazz.parentClass == null && packageName != null) {
sb.append("package ").append(packageName).append(";\n");
}
sb.append("\n").append(initialTabStr).append("public class ")
.append(camelFirstCase(clazz)).append(" {");

for (Entity entity : clazz.entities) {
sb.append("\n").append(initialTabStr).append("\t")
.append(entity.classType).append(" ").append(entity.name)
.append(" ;");
}
for (SubClass subClass : clazz.subClasses) {
sb.append("\n").append(initialTabStr).append("\tList< ")
.append(camelFirstCase(subClass)).append("> ")
.append(camelFirstCase(subClass)).append(" ;");
}
for (SubClass subClass : clazz.subClasses) {
sb.append(initialTabStr).append(generateWholeClass(subClass));
}
sb.append("\n").append(initialTabStr).append("}");
return sb.toString();
}

private static String camelFirstCase(SubClass subClass) {
return subClass.className.substring(0, 1).toUpperCase()
+ subClass.className.substring(1);
}

private static String getInitialTabStr(SubClass clazz) {
if (clazz.parentClass != null) {
return "\t" + getInitialTabStr(clazz.parentClass);
}
return "";
}

/**
* 解析jsonElement
*
* @param clazz
* @param key
* @param jsonElement
*/

private static void parseJsonElement(SubClass clazz, String key,
JsonElement jsonElement)
{

String type;
if (jsonElement.isJsonArray()) {
// json数组
JsonArray jsonArray = jsonElement.getAsJsonArray();
SubClass subClass = new SubClass(key);
clazz.addSubClass(subClass);
parseJsonArray(subClass, key, jsonArray);
} else if (jsonElement.isJsonNull()) {
// 空对象
type = "Object";
clazz.add(new Entity(type, key, null));
System.out.println("Object---" + null);
} else if (jsonElement.isJsonPrimitive()) {
// 基本对象
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
parseJsonPrimitive(clazz, key, jsonPrimitive);
} else if (jsonElement.isJsonObject()) {
// json对象
JsonObject jsonObject = jsonElement.getAsJsonObject();
parseJsonObject(clazz, key, jsonObject);
}
}

/**
* 解析基本数据类型
*
* @param clazz
* @param key
* @param jsonPrimitive
*/

private static void parseJsonPrimitive(SubClass clazz, String key,
JsonPrimitive jsonPrimitive)
{

String type = null;
if (jsonPrimitive.isBoolean()) {
type = "boolean";
System.out.println("boolean " + key + "=" + jsonPrimitive);
} else if (jsonPrimitive.isJsonArray()) {
parseJsonArray(clazz, key, jsonPrimitive.getAsJsonArray());
} else if (jsonPrimitive.isJsonNull()) {
type = "Object";
} else if (jsonPrimitive.isJsonObject()) {
parseJsonObject(clazz, key, jsonPrimitive.getAsJsonObject());
} else if (jsonPrimitive.isNumber()) {
type = "long";
// Number number = jsonPrimitive.getAsNumber();
} else if (jsonPrimitive.isString()) {
type = "String";
} /*
* else if (jsonPrimitive.isJsonPrimitive()) { parseJsonPrimitive(clazz,
* key, jsonPrimitive.getAsJsonPrimitive()); }
*/


// 添加基本类型
if (type != null) {
clazz.add(new Entity(type, key, jsonPrimitive.toString()));
}
}

/**
* 解析对象类型json
*
* @param clazz
* @param key
* @param jsonObject
*/

private static void parseJsonObject(SubClass clazz, String key,
JsonObject jsonObject)
{

for (Entry<string , JsonElement> entry : jsonObject.entrySet()) {
parseJsonElement(clazz, entry.getKey(), entry.getValue());
}
}

/**
* 解析数组类型json
*
* @param clazz
* @param key
* @param jsonArray
*/

private static void parseJsonArray(SubClass clazz, String key,
JsonArray jsonArray)
{

for (int i = 0; i < jsonArray.size(); i++) {
parseJsonElement(clazz, key, jsonArray.get(i));
}
}
}

class SubClass {
String className;
SubClass parentClass;
Set<SubClass> subClasses = new HashSet<>();
Set<entity> entities = new HashSet<>();

public void addSubClass(SubClass subClass) {
subClasses.add(subClass);
subClass.parentClass = this;
}

public SubClass(String className) {
super();
this.className = className;
}

public void add(Entity entity) {
entities.add(entity);
}

@Override
public String toString() {
return "SubClass [className=" + className + ", subClasses="
+ subClasses + ", entities=" + entities + "]";
}

}

class Entity {
String name;
String classType;
String value;

public Entity(String classType, String name, String value) {
super();
this.name = name;
this.classType = classType;
this.value = value;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getClassType() {
return classType;
}

public void setClassType(String classType) {
this.classType = classType;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

@Override
public String toString() {
return classType + " " + name + ";\t";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((classType == null) ? 0 : classType.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Entity other = (Entity) obj;
if (classType == null) {
if (other.classType != null)
return false;
} else if (!classType.equals(other.classType))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

}

json数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"fullname": "Sean Kelly",
"org": "SK Consulting",
"emailaddrs": [
{"type": "work", "value": "kelly@seankelly.biz"},
{"type": "home", "pref": 1, "value": "kelly@seankelly.tv"}
],

"telephones": [
{"type": "work", "pref": 1, "value": "+1 214 555 1212"},
{"type": "fax", "value": "+1 214 555 1213"},
{"type": "mobile", "value": "+1 214 555 1214"}
],

"addresses": [
{"type": "work", "format": "us",
"value": "1234 Main StnSpringfield, TX 78080-1216"},
{"type": "home", "format": "us",
"value": "5678 Main StnSpringfield, TX 78080-1316"}
],

"urls": [
{"type": "work", "value": "http://seankelly.biz/"},
{"type": "home", "value": "http://seankelly.tv/"}
]
}

转换以后的javabean

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
package info.enjoycode.bean;

public class DemoEntity {
String org ;
String fullname ;
List<Addresses> Addresses ;
List<Emailaddrs> Emailaddrs ;
List<Urls> Urls ;
List<Telephones> Telephones ;
public class Addresses {
String value ;
String format ;
String type ;
}
public class Emailaddrs {
String value ;
long pref ;
String type ;
}
public class Urls {
String value ;
String type ;
}
public class Telephones {
String value ;
long pref ;
String type ;
}
}
文章目录
  1. 1. 简介
  2. 2. 代码
  3. 3. json数据
  4. 4. 转换以后的javabean