-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSKAutoJSONToModelShell.py
More file actions
349 lines (278 loc) · 10.7 KB
/
SKAutoJSONToModelShell.py
File metadata and controls
349 lines (278 loc) · 10.7 KB
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# -*-coding:utf-8-*-
__author__ = 'wsk'
import json
import re
import os
import urllib2
import sys
#config file,your can change anything here
yourProjectPrefix = '' #default
yourModelBaseClassName = 'NSObject' #default
#简易的key长度 —— 用于防止各个模块model重复
easyKeyStrCount = 6
#定制化个性model数据结构
isCustomStructModel = 0
if(isCustomStructModel == 1):
yourProjectPrefix = ''
yourModelBaseClassName = 'NSObject'
#default key for list object
defaultListKey = 'responseObject'
#config file name list
jsonFileList = [] #废弃,使用实时请求的方式
#parse by get request url
rootModelName = ''
def getKeyWordByUrl(url):
ret = ''
retList = url.split('?')
if(len(retList) > 0):
newStr = retList[0]
retList = newStr.split('/')
ret = retList[len(retList) - 1]
return ret
def generateModelByHttpGet():
rootPath = os.getcwd()
content = ''
keyWord = ''
flag = 0
flag = raw_input("选择输入的内容类型\n HTTP GET Url【1】\n 或者\n 返回的数据内容【2】\n")
while (cmp('\n', flag) == 0 or len(flag) == 0):
flag = raw_input("输入【1 == URL】【2 == JSON内容】")
while(int(flag) != 1 and int(flag) != 2):
flag = raw_input("类型错误,重新输入")
flag = int(flag)
if(flag == 1):
getUrl = raw_input("输入完整的GET Request Url: ")
while(len(getUrl) == 0):
getUrl = raw_input("url为空,请重新输入")
keyWord = raw_input("输入Model名称(从url获取输入none): ")
while(len(keyWord) == 0):
keyWord = raw_input("model名词为空,请重新输入")
if(keyWord == 'none'):
keyWord = getKeyWordByUrl(getUrl)
else:
keyWord = raw_input("输入Model名称: ")
# response Object 第一个字母小写
# defaultListKey = FirstStrLower(keyWord) + 'Response'
while(len(keyWord) == 0):
keyWord = raw_input("model名词为空,请重新输入")
print "输入Json内容: \n 完成后以回车结束"
while 1:
# 获得用户输入
line = sys.stdin.readline()
if (len(content) > 0 and cmp('\n', line) == 0):
break
else:
line = cleanLineForJsonDecode(line)
content = content + line
global rootModelName
rootModelName = keyWord
global rootKey
rootKey = keyWord
if(len(rootModelName) > 0):
os.chdir(rootPath)
resData = ''
if(flag == 1):
req = urllib2.Request(getUrl)
res_data = urllib2.urlopen(req)
resData = res_data.read()
else:
resData = content
decodejson = json.loads(resData)
rootPath = os.getcwd()
try:
os.makedirs(rootModelName)
except:
tt = ''
os.chdir(rootModelName)
generationFileByDict(rootModelName, transferJsonToDic(decodejson), 0, 1)
print '脚本执行结束,请复制model文件夹到您需要的地方'
else:
print 'model名词为空,无法从 url解析或者 未手动输入'
def cleanLineForJsonDecode(line):
lineStr = line.strip('\n')
lineStr = line.strip()
if(lineStr.count(':') >= 1):
#踢出““数据
mLocation = lineStr.find('"')
if(mLocation != 0):
Location = lineStr.find(':')
sufStr = lineStr[Location :]
dealStr = lineStr[: Location]
#TODO:"如果这边key已经带了""就不要加了
dealStr = "\"" + dealStr + "\""
lineStr = dealStr + sufStr
lineStr.replace("'", "\"")
return lineStr
#parse by file content
#废弃,使用generateModelByHttpGet
def startParseFiles():
#read file content
rootPath = os.getcwd()
for fileName in jsonFileList:
try:
os.chdir(rootPath)
fileFo = open(fileName, 'r')
easyFileContent = ''
for line in fileFo.readlines():
lineStr = cleanLineForJsonDecode(line)
easyFileContent = easyFileContent + lineStr
decodejson = json.loads(easyFileContent)
fileFo.close()
childPath = 'AutoModel://' + fileName
try:
os.makedirs(childPath)
except:
tt = ''
os.chdir(childPath)
generationFileByDict(fileName, transferJsonToDic(decodejson), 0, 1)
except IOError:
print 'can not find your file named' + fileName + IOError.message
def FirstStrBigger(str):
firStr = str[:1]
bodyStr = str[1:]
return firStr.title() + bodyStr
def FirstStrLower(str):
firStr = str[:1]
bodyStr = str[1:]
return firStr.lower() + bodyStr
def generationFileByDict(fileName, aDict, needDicKey, needGenFile):
print u'生成' + fileName + u'model中'
className = ''
if(needDicKey != 2):
className = yourProjectPrefix + FirstStrBigger(fileName).strip() + 'Model'
else:
className = yourProjectPrefix + FirstStrBigger(fileName).strip() + 'ItemModel'
fileName = className + '.h'
if(needGenFile > 0):
OjectCFile = open(fileName,'w')
#write .h file
#@implementation ModelResponseJsonModel
#@end
if(needGenFile > 0):
mFileName = className + '.m'
OjectCMFile = open(mFileName, 'w')
OjectCMFile.write('//\n//Auto ' + className + '.m File \n//From Python Script WSK\n//\n\n')
OjectCMFile.write('#import \"' + className + '.h\"\n\n')
OjectCMFile.write('@implementation ' + className)
OjectCMFile.write('\n')
OjectCMFile.write('\n')
OjectCMFile.write('@end')
OjectCMFile.close()
#define IOS Class Type
protocol = '@protocol'
defaultKey = 'NSString'
IntKey = 'NSNumber'
Strkey = 'NSString'
ListKey = 'NSArray'
#write .h File header
if(needGenFile > 0):
OjectCFile.write('//\n// Auto Create JsonModel File\n// ' + className + '.h' + '\n//\n//\n\n')
OjectCFile.write('#import <Foundation/Foundation.h>\n')
# OjectCFile.write('#import "JSONModel.h"\n')
#need protocol
if(needDicKey == 2):
#@protocol albumListItemModel
#@end
OjectCFile.write('\n@protocol ' + className)
OjectCFile.write('\n\n')
OjectCFile.write('@end\n')
OjectCFile.write(getHeaderFileStr(aDict))
OjectCFile.write('\n')
OjectCFile.write('\n\n@interface ' + className + ' : ' + yourModelBaseClassName)
OjectCFile.write('\n\n')
if(isinstance(aDict, list) or isinstance(aDict, tuple)):
return ""
for key in aDict:
value = aDict[key]
#@property (nonatomic, strong)NSString<Optional> *url;
#@property (nonatomic, strong)NSNumber<Optional> *tagId;
#@property (nonatomic, strong)NSArray<Optional, albumListItemModel> *albumList;
#@property (nonatomic, strong)albumListItemModel<Optional> *testModel;
if(isinstance(value, list) or isinstance(value, tuple)):
protocolKeyJsonM = generationFileByDict(getFileKey(key), parseDicFromList(value), 2, 0)
LineContent = ''
if(len(protocolKeyJsonM) > 0):
generationFileByDict(getFileKey(key), parseDicFromList(value), 2, 1)
LineContent = '\n@property (nonatomic, strong) ' + ListKey + '<' + protocolKeyJsonM + ' >' ' *' + key + ';\n'
else:
LineContent = '@property (nonatomic, strong) ' + ListKey + ' *' + key + ';\n'
if(needGenFile > 0):
OjectCFile.write(LineContent)
#若是数组会加入默认key
elif(isinstance(value, str) or isinstance(value, unicode)):
LineContent = '@property (nonatomic, copy ) ' + Strkey + ' *' + key + ';\n'
if(needGenFile > 0):
OjectCFile.write(LineContent)
elif(isinstance(value, dict)):
objectKey = generationFileByDict(getFileKey(key), value, 1, 1)
LineContent = '\n@property (nonatomic, strong) ' + objectKey + ' *' + key + ';\n'
if(needGenFile > 0):
OjectCFile.write(LineContent)
elif(isinstance(value, int) or isinstance(value, long) or isinstance(value, float)):
LineContent = '@property (nonatomic, strong) ' + IntKey + ' *' + key + ';' + '\n'
if(needGenFile > 0):
OjectCFile.write(LineContent)
else:
#Null or other Object
LineContent = '@property (nonatomic, strong) ' + Strkey + ' *' + key + ';\n'
if(needGenFile > 0):
OjectCFile.write(LineContent)
if(needGenFile > 0):
OjectCFile.write('\n')
OjectCFile.write('@end')
OjectCFile.close()
return className
def refineKey(key):
key = FirstStrBigger(key)
listSubKey = key.split('_')
retKey = ''
for subKey in listSubKey:
subKey = FirstStrBigger(subKey)
retKey = retKey + subKey
return retKey
def getFileKey(key):
global rootModelName
global easyKeyStrCount
if(len(key) <= easyKeyStrCount):
return rootModelName + refineKey(key)
return refineKey(key)
def getHeaderFileStr(aDict):
importStr = ''
if(isinstance(aDict, list) or isinstance(aDict, tuple)):
return ""
for key in aDict:
value = aDict[key]
if(isinstance(value, list) or isinstance(value, tuple)):
protocolKeyJsonM = generationFileByDict(getFileKey(key), parseDicFromList(value), 2, 0)
LineContent = ''
if(len(protocolKeyJsonM) > 0):
importStr = importStr + '#import "' + protocolKeyJsonM + '.h"\n'
elif(isinstance(value, dict)):
objectKey = generationFileByDict(getFileKey(key), value, 1, 0)
importStr = importStr + '#import "' + objectKey + '.h"\n'
return importStr
def parseDicFromList(aList):
#the object in List,here must be Object,and not a string or int/null
if(len(aList) <= 0):
return {'unknow_object_type_in_listObject' : 'list is empty'}
if(isinstance(aList[0], dict)):
return aList[0]
return aList
def transferJsonToDic(decodejson):
#Array List
if(isinstance(decodejson, list)):
tDic = {}
# new add
defaultListKey = FirstStrLower(rootKey) + 'Response'
tDic[defaultListKey] = decodejson
return tDic
#dict
if(isinstance(decodejson, dict)):
#此处可以更改json数据结构,可以定制化model
if(isCustomStructModel == 1):
for key in decodejson:
if(key == 'data'):
return decodejson['data']
return decodejson
return {'newParseError' : 'content is invalid'}
generateModelByHttpGet()