Skip to content

Commit d96c22d

Browse files
committed
修复json中字段不存在或者为null时可能导致的bean对象创建错误,也就是各字段处理时加入了null判断;放弃对于普通数据类型数组的生成代码优化;更新测试
1 parent 92954fa commit d96c22d

File tree

7 files changed

+99
-87
lines changed

7 files changed

+99
-87
lines changed

Test/EmptyResp.dart

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ class EmptyResp {
66

77
EmptyResp.fromParams({this.qwe});
88

9-
factory EmptyResp(jsonStr) => jsonStr is String ? EmptyResp.fromJson(json.decode(jsonStr)) : EmptyResp.fromJson(jsonStr);
9+
factory EmptyResp(jsonStr) => jsonStr == null ? null : jsonStr is String ? new EmptyResp.fromJson(json.decode(jsonStr)) : new EmptyResp.fromJson(jsonStr);
1010

1111
EmptyResp.fromJson(jsonRes) {
12-
qwe = new Qwe.fromJson(jsonRes['qwe']);
12+
qwe = jsonRes['qwe'] == null ? null : new Qwe.fromJson(jsonRes['qwe']);
1313
}
1414

1515
@override
@@ -27,17 +27,21 @@ class Qwe {
2727
Qwe.fromParams({this.asd, this.qaz, this.zxc});
2828

2929
Qwe.fromJson(jsonRes) {
30-
asd = [];
30+
asd = jsonRes['asd'] == null ? null : [];
3131

32-
for (var asdItem in jsonRes['asd']){
32+
for (var asdItem in asd == null ? [] : jsonRes['asd']){
3333
asd.add(asdItem);
3434
}
3535

36-
qaz = jsonRes['qaz'].cast<Object>();
36+
qaz = jsonRes['qaz'] == null ? null : [];
3737

38-
zxc = [];
38+
for (var qazItem in qaz == null ? [] : jsonRes['qaz']){
39+
qaz.add(qazItem);
40+
}
41+
42+
zxc = jsonRes['zxc'] == null ? null : [];
3943

40-
for (var zxcItem in jsonRes['zxc']){
44+
for (var zxcItem in zxc == null ? [] : jsonRes['zxc']){
4145
zxc.add(zxcItem);
4246
}
4347
}

Test/ListsResp.dart

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,33 +8,37 @@ class ListsResp {
88

99
ListsResp.fromParams({this.asd, this.qaz, this.qwe});
1010

11-
factory ListsResp(jsonStr) => jsonStr is String ? ListsResp.fromJson(json.decode(jsonStr)) : ListsResp.fromJson(jsonStr);
11+
factory ListsResp(jsonStr) => jsonStr == null ? null : jsonStr is String ? new ListsResp.fromJson(json.decode(jsonStr)) : new ListsResp.fromJson(jsonStr);
1212

1313
ListsResp.fromJson(jsonRes) {
14-
asd = [];
14+
asd = jsonRes['asd'] == null ? null : [];
1515

16-
for (var asdItem in jsonRes['asd']){
17-
List<List<int>> asdChild = [];
18-
for (var asdItemItem in asdItem){
19-
List<int> asdChildChild = [];
20-
for (var asdItemItemItem in asdItemItem){
16+
for (var asdItem in asd == null ? [] : jsonRes['asd']){
17+
List<List<int>> asdChild = asdItem == null ? null : [];
18+
for (var asdItemItem in asdChild == null ? [] : asdItem){
19+
List<int> asdChildChild = asdItemItem == null ? null : [];
20+
for (var asdItemItemItem in asdChildChild == null ? [] : asdItemItem){
2121
asdChildChild.add(asdItemItemItem);
2222
}
2323
asdChild.add(asdChildChild);
2424
}
2525
asd.add(asdChild);
2626
}
2727

28-
qaz = jsonRes['qaz'].cast<int>();
28+
qaz = jsonRes['qaz'] == null ? null : [];
2929

30-
qwe = [];
30+
for (var qazItem in qaz == null ? [] : jsonRes['qaz']){
31+
qaz.add(qazItem);
32+
}
33+
34+
qwe = jsonRes['qwe'] == null ? null : [];
3135

32-
for (var qweItem in jsonRes['qwe']){
33-
List<List<Zxc>> qweChild = [];
34-
for (var qweItemItem in qweItem){
35-
List<Zxc> qweChildChild = [];
36-
for (var qweItemItemItem in qweItemItem){
37-
qweChildChild.add(new Zxc.fromJson(qweItemItemItem));
36+
for (var qweItem in qwe == null ? [] : jsonRes['qwe']){
37+
List<List<Zxc>> qweChild = qweItem == null ? null : [];
38+
for (var qweItemItem in qweChild == null ? [] : qweItem){
39+
List<Zxc> qweChildChild = qweItemItem == null ? null : [];
40+
for (var qweItemItemItem in qweChildChild == null ? [] : qweItemItem){
41+
qweChildChild.add(qweItemItemItem == null ? null : new Zxc.fromJson(qweItemItemItem));
3842
}
3943
qweChild.add(qweChildChild);
4044
}

Test/RegionResp.dart

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ class RegionResp {
99

1010
RegionResp.fromParams({this.code, this.ttl, this.message, this.data});
1111

12-
factory RegionResp(jsonStr) => jsonStr is String ? RegionResp.fromJson(json.decode(jsonStr)) : RegionResp.fromJson(jsonStr);
12+
factory RegionResp(jsonStr) => jsonStr == null ? null : jsonStr is String ? new RegionResp.fromJson(json.decode(jsonStr)) : new RegionResp.fromJson(jsonStr);
1313

1414
RegionResp.fromJson(jsonRes) {
1515
code = jsonRes['code'];
1616
ttl = jsonRes['ttl'];
1717
message = jsonRes['message'];
18-
data = new Data.fromJson(jsonRes['data']);
18+
data = jsonRes['data'] == null ? null : new Data.fromJson(jsonRes['data']);
1919
}
2020

2121
@override
@@ -32,13 +32,13 @@ class Data {
3232
Data.fromParams({this.archives, this.page});
3333

3434
Data.fromJson(jsonRes) {
35-
archives = [];
35+
archives = jsonRes['archives'] == null ? null : [];
3636

37-
for (var archivesItem in jsonRes['archives']){
38-
archives.add(new Arch.fromJson(archivesItem));
37+
for (var archivesItem in archives == null ? [] : jsonRes['archives']){
38+
archives.add(archivesItem == null ? null : new Arch.fromJson(archivesItem));
3939
}
4040

41-
page = new Page.fromJson(jsonRes['page']);
41+
page = jsonRes['page'] == null ? null : new Page.fromJson(jsonRes['page']);
4242
}
4343

4444
@override
@@ -104,9 +104,9 @@ class Arch {
104104
pic = jsonRes['pic'];
105105
title = jsonRes['title'];
106106
tname = jsonRes['tname'];
107-
owner = new Owner.fromJson(jsonRes['owner']);
108-
rights = new Rights.fromJson(jsonRes['rights']);
109-
stat = new Stat.fromJson(jsonRes['stat']);
107+
owner = jsonRes['owner'] == null ? null : new Owner.fromJson(jsonRes['owner']);
108+
rights = jsonRes['rights'] == null ? null : new Rights.fromJson(jsonRes['rights']);
109+
stat = jsonRes['stat'] == null ? null : new Stat.fromJson(jsonRes['stat']);
110110
}
111111

112112
@override

Test/WanResp.dart

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,25 @@ class WanResp {
88

99
WanResp.fromParams({this.errorCode, this.errorMsg, this.data});
1010

11-
factory WanResp(jsonStr) => jsonStr is String ? WanResp.fromJson(json.decode(jsonStr)) : WanResp.fromJson(jsonStr);
11+
factory WanResp(jsonStr) =>
12+
jsonStr == null ? null : jsonStr is String ? new WanResp.fromJson(json.decode(jsonStr)) : new WanResp.fromJson(
13+
jsonStr);
1214

1315
WanResp.fromJson(jsonRes) {
1416
errorCode = jsonRes['errorCode'];
1517
errorMsg = jsonRes['errorMsg'];
16-
data = [];
18+
data = jsonRes['data'] == null ? null : [];
1719

18-
for (var dataItem in jsonRes['data']){
19-
data.add(new Data.fromJson(dataItem));
20+
for (var dataItem in data == null ? [] : jsonRes['data']) {
21+
data.add(dataItem == null ? null : new Data.fromJson(dataItem));
2022
}
2123
}
2224

2325
@override
2426
String toString() {
25-
return '{"errorCode": $errorCode,"errorMsg": ${errorMsg != null?'${json.encode(errorMsg)}':'null'},"data": $data}';
27+
return '{"errorCode": $errorCode,"errorMsg": ${errorMsg != null
28+
? '${json.encode(errorMsg)}'
29+
: 'null'},"data": $data}';
2630
}
2731
}
2832

@@ -45,16 +49,17 @@ class Data {
4549
parentChapterId = jsonRes['parentChapterId'];
4650
visible = jsonRes['visible'];
4751
name = jsonRes['name'];
48-
children = [];
52+
children = jsonRes['children'] == null ? null : [];
4953

50-
for (var childrenItem in jsonRes['children']){
51-
children.add(new Children.fromJson(childrenItem));
54+
for (var childrenItem in children == null ? [] : jsonRes['children']) {
55+
children.add(childrenItem == null ? null : new Children.fromJson(childrenItem));
5256
}
5357
}
5458

5559
@override
5660
String toString() {
57-
return '{"courseId": $courseId,"id": $id,"order": $order,"parentChapterId": $parentChapterId,"visible": $visible,"name": ${name != null?'${json.encode(name)}':'null'},"children": $children}';
61+
return '{"courseId": $courseId,"id": $id,"order": $order,"parentChapterId": $parentChapterId,"visible": $visible,"name": ${name !=
62+
null ? '${json.encode(name)}' : 'null'},"children": $children}';
5863
}
5964
}
6065

@@ -68,7 +73,8 @@ class Children {
6873
String name;
6974
List<dynamic> children;
7075

71-
Children.fromParams({this.courseId, this.id, this.order, this.parentChapterId, this.visible, this.name, this.children});
76+
Children.fromParams(
77+
{this.courseId, this.id, this.order, this.parentChapterId, this.visible, this.name, this.children});
7278

7379
Children.fromJson(jsonRes) {
7480
courseId = jsonRes['courseId'];
@@ -77,16 +83,17 @@ class Children {
7783
parentChapterId = jsonRes['parentChapterId'];
7884
visible = jsonRes['visible'];
7985
name = jsonRes['name'];
80-
children = [];
86+
children = jsonRes['children'] == null ? null : [];
8187

82-
for (var childrenItem in jsonRes['children']){
83-
children.add(childrenItem);
88+
for (var childrenItem in children == null ? [] : jsonRes['children']) {
89+
children.add(childrenItem);
8490
}
8591
}
8692

8793
@override
8894
String toString() {
89-
return '{"courseId": $courseId,"id": $id,"order": $order,"parentChapterId": $parentChapterId,"visible": $visible,"name": ${name != null?'${json.encode(name)}':'null'},"children": $children}';
95+
return '{"courseId": $courseId,"id": $id,"order": $order,"parentChapterId": $parentChapterId,"visible": $visible,"name": ${name !=
96+
null ? '${json.encode(name)}' : 'null'},"children": $children}';
9097
}
9198
}
9299

Test/test.dart

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,32 @@ import 'WanResp.dart';
88
import 'ListsResp.dart';
99

1010
void main() {
11+
12+
test('Test null', (){
13+
String str0 = '{"asd":[[[1]]],"qwe":[[[{"zxc":1}]]],"qaz":[1]}';
14+
String str1 = '{"asd":[[[null,null]]],"qwe":[[[null]]],"qaz":[null,null,null]}';
15+
String str2 = '{"asd":[[[]]],"qwe":[[[{"zxc":null}]]],"qaz":[null]}';
16+
String str3 = '{"asd":[[]],"qwe":[[[]]],"qaz":null}';
17+
String str4 = '{"asd":[],"qwe":[[]],"qaz":null}';
18+
String str5 = '{"asd":null,"qwe":[],"qaz":null}';
19+
String str6;
20+
expect(json.decode(new ListsResp(str0).toString()), json.decode(str0));
21+
expect(json.decode(new ListsResp(str1).toString()), json.decode(str1));
22+
expect(json.decode(new ListsResp(str2).toString()), json.decode(str2));
23+
expect(json.decode(new ListsResp(str3).toString()), json.decode(str3));
24+
expect(json.decode(new ListsResp(str4).toString()), json.decode(str4));
25+
expect(json.decode(new ListsResp(str5).toString()), json.decode(str5));
26+
expect(json.decode(new ListsResp(str6).toString()), null);
27+
28+
});
1129
test('Test Region', () {
1230
String str = readFromFile('Region');
1331
RegionResp resp = new RegionResp(str);
1432
var jsonRes = json.decode(str);
1533

34+
/// 测试传入String和json进行解析的结果是否相同
35+
expect(resp.toString(), new RegionResp(jsonRes).toString());
36+
1637
/// 逐个字段检查是否与json.decode()的结果相同
1738
expect(resp.code, jsonRes['code']);
1839
expect(resp.message, jsonRes['message']);
@@ -103,6 +124,9 @@ void main() {
103124
WanResp resp = new WanResp(str);
104125
var jsonRes = json.decode(str);
105126

127+
/// 测试传入String和json进行解析的结果是否相同
128+
expect(resp.toString(), new WanResp(jsonRes).toString());
129+
106130
/// 逐个字段检查是否与json.decode()的结果相同
107131
expect(resp.errorCode, jsonRes['errorCode']);
108132
expect(resp.errorMsg, jsonRes['errorMsg']);
@@ -146,6 +170,9 @@ void main() {
146170
EmptyResp resp = new EmptyResp(str);
147171
var jsonRes = json.decode(str);
148172

173+
/// 测试传入String和json进行解析的结果是否相同
174+
expect(resp.toString(), new EmptyResp(jsonRes).toString());
175+
149176
/// 逐个字段检查是否与json.decode()的结果相同
150177
expect(resp.qwe.asd, jsonRes['qwe']['asd']);
151178
expect(resp.qwe.zxc, jsonRes['qwe']['zxc']);
@@ -162,6 +189,9 @@ void main() {
162189
ListsResp resp = new ListsResp(str);
163190
var jsonRes = json.decode(str);
164191

192+
/// 测试传入String和json进行解析的结果是否相同
193+
expect(resp.toString(), new ListsResp(jsonRes).toString());
194+
165195
/// 逐个字段检查是否与json.decode()的结果相同
166196
expect(resp.asd[0][0][0], jsonRes['asd'][0][0][0]);
167197
expect(resp.qwe[0][0][0].zxc, jsonRes['qwe'][0][0][0]['zxc']);

template_code.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ class ${type} {
2525
2626
"""
2727

28-
template_list = r"""
29-
${list_count}${class_type}${>count} ${name}${current_child} = [];
30-
for (var ${name}${current_items} in ${name}${parent_items}){
28+
template_list = r"""
29+
${list_count}${class_type}${>count} ${name}${current_child} = ${name}${parent_items} == null ? null : [];
30+
for (var ${name}${current_items} in ${name}${current_child} == null ? [] : ${name}${parent_items}){
3131
${loop}
3232
${name}${current_child}.add(${name}${child_child});
3333
}

tools.py

Lines changed: 6 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def list_code_loop(code, count, total, n, ct):
6767
def build_list_construction(t, n):
6868
class_type = t.replace('List<', '').replace('>', '')
6969

70-
list_loop = '[];\n'
70+
list_loop = 'jsonRes[\'%s\'] == null ? null : [];\n' % n
7171
assert isinstance(t, str)
7272

7373
code = ''
@@ -78,7 +78,8 @@ def build_list_construction(t, n):
7878

7979
# 嵌套模板的后续处理
8080
if check_level_type(class_type) not in (1, 2) and class_type != '':
81-
code = code.replace('%s%s' % (n, 'Child' * total), 'new %s.fromJson(%s%s)' % (class_type, n, ('Item' * total)))
81+
code = code.replace('%s%s' % (n, 'Child' * total), '%s%s == null ? null : new %s.fromJson(%s%s)'
82+
% (n, ('Item' * total), class_type, n, ('Item' * total)))
8283
else:
8384
code = code.replace('%s' % ('Child' * total), '%s' % ('Item' * total))
8485
code = code[code.find(';') + 1:]
@@ -117,7 +118,7 @@ def add_param_to_code(code, param):
117118

118119
# dict类型处理,只需要修改construction中的输出方式
119120
elif t_code == 4:
120-
code = code.replace('jsonRes[\'%s\']' % f, 'new %s.fromJson(jsonRes[\'%s\'])' % (t, f))
121+
code = code.replace('jsonRes[\'%s\']' % f, 'jsonRes[\'%s\'] == null ? null : new %s.fromJson(jsonRes[\'%s\'])' % (f, t, f))
121122

122123
# list类型处理,只需要修改construction中的输出方式
123124
elif t_code == 3:
@@ -200,44 +201,9 @@ def generate_code(work_bean):
200201
# 移除参数构造函数用模板生成后多余的逗号和空格
201202
res = res.replace(', });', '});')
202203

203-
# 利用利用大括号匹配移除无用行的计数器
204-
remove_counter = 0
205-
need_clean = False
206-
207204
# 移除没有必要的list取值循环
208205
lines = res.splitlines()
209206
for index in range(len(lines)):
210-
if r' = [];' in lines[index] and r'List<' not in lines[index]:
211-
field_name = lines[index].strip()
212-
field_name = field_name[:field_name.find(' ')]
213-
need_clean = False
214-
for revert_index in range(index - 1, 0, -1):
215-
if r'> %s;' % field_name in lines[revert_index]:
216-
field_type = lines[revert_index]
217-
field_type = field_type[field_type.find('<') + 1:field_type.rfind('>')]
218-
if check_level_type(field_type) in (1, 2):
219-
# List的类型或嵌套类型为基本数据类型
220-
need_clean = True
221-
break
222-
if need_clean:
223-
# 利用大括号匹配移除无用行
224-
sp = lines[index + 2].find('in ')
225-
ep = lines[index + 2].rfind(')')
226-
list_src = lines[index + 2][sp + 3:ep] + '.cast<%s>()' % field_type
227-
lines[index] = lines[index].replace('[]', list_src)
228-
continue
229-
230-
if need_clean:
231-
lines[index] = '//%s' % lines[index]
232-
if lines[index].strip() == '//':
233-
continue
234-
if lines[index].strip().endswith('{'):
235-
remove_counter += 1
236-
if lines[index].strip().endswith('}'):
237-
remove_counter -= 1
238-
if remove_counter == 0:
239-
need_clean = False
240-
241207
if lines[index].strip() == '' and index < len(lines) - 1 and lines[index + 1].strip() in ('', '}'):
242208
lines[index] = '//%s' % lines[index]
243209

@@ -250,7 +216,8 @@ def generate_code(work_bean):
250216
out_res += (line + '\n')
251217
if first and r'.fromParams({this.' in line:
252218
class_name = line.split(r'.fromParams({this.')[0].strip()
253-
out_res += '\n factory %s(jsonStr) => jsonStr is String ? %s.fromJson(json.decode(jsonStr)) : %s.fromJson(jsonStr);\n' \
219+
out_res += '\n factory %s(jsonStr) => jsonStr == null ? null : jsonStr is String ? new %s.fromJson(json.decode(jsonStr)) : ' \
220+
'new %s.fromJson(jsonStr);\n' \
254221
% (class_name, class_name, class_name)
255222
first = False
256223
return out_res

0 commit comments

Comments
 (0)