移动架构之json解析框架

JSON在现在数据传输中占据着重要地位,相比于xml,其解析和构成都要简单很多,第三方的解析框架也不胜枚举,这里之所以要自定义一个json解析框架,一方面是更好的了解json解析过程,另一方面是有时候需要对解析出来的json数据做转换

实现的功能

json转model,model转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
public class FastJson {
public static final int JSON_ARRAY = 1;
public static final int JSON_OBJECT = 2;
public static final int JSON_ERRO = 3;

//调用层调用
public static Object pareseObject(String json, Class clazz) {
Object object = null;
Class<?> jsonClass = null;
//JSONArray类型
if (json.charAt(0) == '[') {
try {
object = toList(json, clazz);
} catch (JSONException e) {
e.printStackTrace();
}
} else if (json.charAt(0) == '{') {
try {
JSONObject jsonObject = new JSONObject(json);
//反射得到最外层的model
object = clazz.newInstance();
//得到的最外层的key集合
Iterator<?> iterator = jsonObject.keys();
//遍历集合
while (iterator.hasNext()) {
String key = (String) iterator.next();
Object fieldValue = null;
//得到当前clazz类型的所有成员变量
List<Field> fields = getAllFields(clazz, null);
for (Field field : fields) {
//将key和成员变量进行匹配
if (field.getName().equalsIgnoreCase(key)) {
field.setAccessible(true);
//得到key所对应的值
fieldValue = getFieldValue(field, jsonObject, key);
if (fieldValue != null) {
field.set(object, fieldValue);
}
field.setAccessible(false);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return object;
}

//得到当前的value值
private static Object getFieldValue(Field field, JSONObject jsonObject, String key) throws JSONException {
Object fieldValue = null;
//得到当前成员变量类型
Class<?> fieldClass = field.getType();
if (fieldClass.getSimpleName().toString().equals("int")
|| fieldClass.getSimpleName().toString().equals("Integer")) {
fieldValue = jsonObject.getInt(key);
} else if (fieldClass.getSimpleName().toString().equals("double")
|| fieldClass.getSimpleName().toString().equals("Double")) {
fieldValue = jsonObject.getDouble(key);
} else if (fieldClass.getSimpleName().toString().equals("boolean")
|| fieldClass.getSimpleName().toString().equals("Boolean")) {
fieldValue = jsonObject.getBoolean(key);
} else if (fieldClass.getSimpleName().toString().equals("long")
|| fieldClass.getSimpleName().toString().equals("Long")) {
fieldValue = jsonObject.getLong(key);
} else if (fieldClass.getSimpleName().toString().equals("String")) {
fieldValue = jsonObject.getString(key);
} else {
//判断集合类型和对象类型
String jsonValue = jsonObject.getString(key);
switch (getJSONType(jsonValue)) {
case JSON_ARRAY:
Type fieldType = field.getGenericType();
if (fieldType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) fieldType;
//当前类所实现的泛型
Type[] fieldArgType = parameterizedType.getActualTypeArguments();
for (Type type : fieldArgType) {
Class<?> fieldArgClass = (Class<?>) type;
fieldValue = toList(jsonValue, fieldArgClass);
}
}
break;
case JSON_OBJECT:
//fieldClass成员变量类型
fieldValue = pareseObject(jsonValue, fieldClass);
break;
case JSON_ERRO:
break;
}
}
return fieldValue;
}

//获取当前json字符串的类型
private static int getJSONType(String jsonValue) {
char firstChar = jsonValue.charAt(0);
if (firstChar == '{') {
return JSON_OBJECT;
} else if (firstChar == '[') {
return JSON_ARRAY;
} else {
return JSON_ERRO;
}
}

//解析JsonArray数组
private static Object toList(String json, Class clazz) throws JSONException {
List<Object> list = null;
JSONArray jsonArray = new JSONArray(json);
list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
//拿到JSON字符串
String jsonValue = jsonArray.getJSONObject(i).toString();
switch (getJSONType(jsonValue)) {
case JSON_ARRAY:
//外层JSONArray嵌套里面JSONArray
List<?> infoList = (List<?>) toList(jsonValue, clazz);
list.add(infoList);
break;
case JSON_OBJECT:
list.add(pareseObject(jsonValue, clazz));
break;
case JSON_ERRO:
break;
}
}
return list;
}

public static String toJson(Object object) {
//JSON载体
StringBuilder jsonBuilder = new StringBuilder();
//判断是否是集合类型
if (object instanceof List<?>) {
jsonBuilder.append("[");
List<?> list = (List<?>) object;
//获取集合类型
for (int i = 0; i < list.size(); i++) {
//解析成JSONObject类型
addObjectToJson(jsonBuilder, list.get(i));
if (i < list.size() - 1) {
jsonBuilder.append(",");
}
}
} else {
addObjectToJson(jsonBuilder, object);
}
return jsonBuilder.toString();
}

//解析单独的JSONObject类型
private static void addObjectToJson(StringBuilder jsonBuilder, Object o) {
jsonBuilder.append("{");
List<Field> fields = new ArrayList<>();
getAllFields(o.getClass(), fields);
for (int i = 0; i < fields.size(); i++) {
//代表get方法
Method method = null;
Field field = fields.get(i);
String fieldName = field.getName();
Object fieldValue = null;
//get类型方法
String methodName = "get" + ((char) (fieldName.charAt(0) - 0x20) + fieldName.substring(1));
try {
//得到method对象
method = o.getClass().getMethod(methodName);
} catch (NoSuchMethodException e) {
//is类型方法
methodName = "is" + ((char) (fieldName.charAt(0) - 0x20) + fieldName.substring(1));
try {
method = o.getClass().getMethod(methodName);
} catch (NoSuchMethodException e1) {
}
}
if (method != null) {
try {
fieldValue = method.invoke(o);
} catch (Exception e) {
e.printStackTrace();
}
}
if (fieldValue != null) {
jsonBuilder.append("\"");
jsonBuilder.append(fieldName);
jsonBuilder.append("\":");
if (fieldValue instanceof Integer
|| fieldValue instanceof Double
|| fieldValue instanceof Long
|| fieldValue instanceof Boolean) {
jsonBuilder.append(fieldValue.toString());
} else if (fieldValue instanceof String) {
jsonBuilder.append("\"");
jsonBuilder.append(fieldValue.toString());
jsonBuilder.append("\"");
} else if (fieldValue instanceof List<?>) {
addListToBuffer(jsonBuilder, fieldValue);
} else {
//类类型
addObjectToJson(jsonBuilder, fieldValue);
}
jsonBuilder.append(",");
}
if (i == fields.size() - 1 && jsonBuilder.charAt(jsonBuilder.length() - 1) == ',') {
jsonBuilder.deleteCharAt(jsonBuilder.length() - 1);
}
}
jsonBuilder.append("}");
}

//解析集合类型数据
private static void addListToBuffer(StringBuilder jsonBuilder, Object fieldValue) {
List<?> list = (List<?>) fieldValue;
jsonBuilder.append("[");
for (int i = 0; i < list.size(); i++) {
addObjectToJson(jsonBuilder, list.get(i));
if (i < list.size() - 1) {
jsonBuilder.append(",");
}
}
jsonBuilder.append("]");
}

//获取当前Class所有成员变量
private static List<Field> getAllFields(Class<?> aClass, List<Field> fields) {
if (fields == null) {
fields = new ArrayList<>();
}
//排除Object类型
if (aClass.getSuperclass() != null) {
//拿到当前Class的所有成员变量的Field
Field[] fieldsSelf = aClass.getDeclaredFields();
for (Field field : fieldsSelf) {
//排除final修饰的成员变量
if (!Modifier.isFinal(field.getModifiers())) {
fields.add(field);
}
}
getAllFields(aClass.getSuperclass(), fields);
}
return fields;
}
}

测试的model类

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
public class News {
private int id;
private String title;
private String content;
private User author;
private boolean isCancle;
private List<User> reader;

public News() {
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public User getAuthor() {
return author;
}

public void setAuthor(User author) {
this.author = author;
}

public boolean isCancle() {
return isCancle;
}

public void setCancle(boolean cancle) {
isCancle = cancle;
}

public List<User> getReader() {
return reader;
}

public void setReader(List<User> reader) {
this.reader = reader;
}

@Override
public String toString() {
return "News [id=" + id + ", title=" + title + ", content=" + content
+ ", author=" + author + ", isCancle=" + isCancle + ", reader=" + reader + "]";
}
}

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
public class User {
private int id;
private String name;
private String password;

public User() {
}

public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

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

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
}
}

调用测试

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
public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";
private News news;
private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
}

public void modelToJson(View view) {
setNews();
String json = FastJson.toJson(news);
textView.append(json);
textView.append("\n\n");
}

public void jsonToModel(View view) {
String json = FastJson.toJson(news);
News news = (News) FastJson.pareseObject(json, News.class);
textView.append(news.toString());
textView.append("\n\n");
}

public void cleanText(View view) {
textView.setText("");
}

private void setNews(){
news = new News();
news.setId(1);
news.setTitle("Test Title");
news.setContent("Test Content");
news.setCancle(true);
news.setAuthor(createAuthor());
news.setReader(createReaders());
}

private static List<User> createReaders() {
List<User> readers = new ArrayList<User>();
User readerA = new User();
readerA.setId(2);
readerA.setName("Jack");
readers.add(readerA);
User readerB = new User();
readerB.setId(1);
readerB.setName("Bob");
readerB.setPassword("123456");
readers.add(readerB);
return readers;
}

private static User createAuthor() {
User author = new User();
author.setId(1);
author.setName("Alen");
author.setPassword("123456");
return author;
}
}

测试结果如图所示

Donate comment here