├── .gitattributes ├── .gitignore ├── LICENSE ├── Product ├── WliuModel.h └── WliuModel.m ├── README.md ├── dome_sheet.gif └── oc_json_plugin.py /.gitattributes: -------------------------------------------------------------------------------- 1 | *.py linguist-language=Objective-C 2 | *.md linguist-language=Objective-C 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | build/ 4 | *.pbxuser 5 | !default.pbxuser 6 | *.mode1v3 7 | !default.mode1v3 8 | *.mode2v3 9 | !default.mode2v3 10 | *.perspectivev3 11 | !default.perspectivev3 12 | xcuserdata 13 | *.xccheckout 14 | *.moved-aside 15 | DerivedData 16 | *.hmap 17 | *.ipa 18 | *.xcuserstate 19 | 20 | # CocoaPods 21 | # 22 | # We recommend against adding the Pods directory to your .gitignore. However 23 | # you should judge for yourself, the pros and cons are mentioned at: 24 | # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control 25 | # 26 | #Pods/ 27 | 28 | 29 | # Mac 30 | *.DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 wliu 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. -------------------------------------------------------------------------------- /Product/WliuModel.h: -------------------------------------------------------------------------------- 1 | /*! 2 | * producted by oc_json_plugin.py 3 | * auth: w6 4 | */ 5 | #import 6 | 7 | @interface WliuTeam : NSObject 8 | 9 | @property (nonatomic, assign) NSInteger count; 10 | 11 | @property (nonnull, nonatomic, copy) NSString *name; 12 | 13 | - (_Nonnull instancetype)initWithWliuTeamDic:(NSDictionary * _Nonnull)infoDic; 14 | 15 | @end 16 | 17 | @interface WliuResult : NSObject 18 | 19 | @property (nonnull, nonatomic, copy) NSString *url; 20 | 21 | @property (nonnull, nonatomic, copy) NSString *content; 22 | 23 | @property (nonnull, nonatomic, copy) NSString *version; 24 | 25 | @property (nonatomic, assign) float filesize; 26 | 27 | @property (nonatomic, assign) NSInteger isforce; 28 | 29 | - (_Nonnull instancetype)initWithWliuResultDic:(NSDictionary * _Nonnull)infoDic; 30 | 31 | @end 32 | 33 | @interface WliuBaseModel : NSObject 34 | 35 | @property (nonnull, nonatomic, strong) WliuResult *result; 36 | 37 | @property (nonnull, nonatomic, strong) NSArray *team; 38 | 39 | @property (nonatomic, assign) float xxasdaa; 40 | 41 | @property (nonatomic, assign) NSInteger style; 42 | 43 | @property (nonnull, nonatomic, copy) NSString *code; 44 | 45 | @property (nonnull, nonatomic, copy) NSString *message; 46 | 47 | - (_Nonnull instancetype)initWithWliuBaseModelDic:(NSDictionary * _Nonnull)infoDic; 48 | 49 | @end 50 | -------------------------------------------------------------------------------- /Product/WliuModel.m: -------------------------------------------------------------------------------- 1 | /*! 2 | * producted by oc_json_plugin.py 3 | * auth: w6 4 | */ 5 | #import "WliuModel.h" 6 | 7 | @implementation WliuTeam 8 | 9 | - (instancetype)initWithWliuTeamDic:(NSDictionary *)infoDic { 10 | self = [super init]; 11 | if (self) { 12 | if (infoDic) { 13 | _count = [[infoDic objectForKey:@"count"] integerValue]; 14 | _name = [infoDic objectForKey:@"name"]; 15 | 16 | } 17 | } 18 | return self; 19 | } 20 | 21 | @end 22 | 23 | 24 | 25 | @implementation WliuResult 26 | 27 | - (instancetype)initWithWliuResultDic:(NSDictionary *)infoDic { 28 | self = [super init]; 29 | if (self) { 30 | if (infoDic) { 31 | _url = [infoDic objectForKey:@"url"]; 32 | _content = [infoDic objectForKey:@"content"]; 33 | _version = [infoDic objectForKey:@"version"]; 34 | _filesize = [[infoDic objectForKey:@"filesize"] floatValue]; 35 | _isforce = [[infoDic objectForKey:@"isforce"] integerValue]; 36 | 37 | } 38 | } 39 | return self; 40 | } 41 | 42 | @end 43 | 44 | 45 | 46 | @implementation WliuBaseModel 47 | 48 | - (instancetype)initWithWliuBaseModelDic:(NSDictionary *)infoDic { 49 | self = [super init]; 50 | if (self) { 51 | if (infoDic) { 52 | _result = [infoDic objectForKey:@"result"]; 53 | 54 | NSMutableArray *resultArr = [@[] mutableCopy]; 55 | NSArray *targetArr = [infoDic objectForKey:@"team"]; 56 | for (NSDictionary *dic in targetArr) { 57 | WliuTeam *obj = [[WliuTeam alloc] initWithWliuTeamDic:dic]; 58 | [resultArr addObject:obj]; 59 | } 60 | _team = [resultArr copy]; 61 | _xxasdaa = [[infoDic objectForKey:@"xxasdaa"] floatValue]; 62 | _style = [[infoDic objectForKey:@"style"] integerValue]; 63 | _code = [infoDic objectForKey:@"code"]; 64 | _message = [infoDic objectForKey:@"message"]; 65 | 66 | } 67 | } 68 | return self; 69 | } 70 | 71 | @end 72 | 73 | 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # **OC_JSON_Plugin** 2 | ###*blog:<>* 3 | *** 4 | * [English Description](#English Description) 5 | * [中文说明](#中文说明) 6 | 7 | 8 | ## 这是干啥的? 9 | JSON 转 Model 的脚本 10 | 11 | ## 面向人群 12 | fat model 使用人群 13 | 14 | ## 使用 15 | 1.`cd 'oc_json_plugin.py文件所在路径'` 16 | 17 | 2.`python oc_json_plugin.py` 18 | 19 | ![Screenshot](https://github.com/wliu6/OC_JSON_Plugin/blob/master/dome_sheet.gif) 20 | 21 | ####Note: 22 | 23 | * `python oc_json_plugin.py -d`在.h文件显示对应字段的json 24 | 25 | ## 其他: 26 | 27 | * 如在使用过程中需要到问题,请你Issues我。 28 | * 有什么好的想法也可以Issues我。 29 | * 如果你没有男票而且想交男票请一定Issues我!!! 30 | 31 | #### 特别感谢: 32 | * [ESJSONFormat](https://github.com/EnjoySR/ESJsonFormat-Xcode) 因为之前用的很舒服,知道Xcode8之后不能用了之后让我萌生了写这个脚本的想法。 33 | -------------------------------------------------------------------------------- /dome_sheet.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wliu6/OC_JSON_Plugin/535c9fc9daf6240bdc7381875093f1a258b14202/dome_sheet.gif -------------------------------------------------------------------------------- /oc_json_plugin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Created by ibireme on 13/3/30. 3 | # Copyright (c) 2015 ibireme. 4 | # This source code is licensed under the MIT-style license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | # Params 8 | import argparse 9 | parser = argparse.ArgumentParser() 10 | parser.add_argument("-ks", help="kszc use!", action='store_true') 11 | parser.add_argument("-d", help="Whether show the original data of JSON.", action='store_true') 12 | args = parser.parse_args() 13 | ks_use = args.ks 14 | wliu_desc = args.d 15 | 16 | class oc_files_manager(object): 17 | """docstring for oc_files_manager""" 18 | __slots__ = ('h_file_content', 'm_file_content') 19 | 20 | def __init__(self, **kw): 21 | super(oc_files_manager, self).__init__() 22 | for key, value in kw.iteritems(): 23 | if key == 'h_file_content': 24 | self.h_file_content = value 25 | elif key == 'm_file_content': 26 | self.m_file_content = value 27 | else: 28 | pass 29 | 30 | # Json 31 | try: 32 | import json 33 | except ImportError: 34 | import simplejson as json 35 | 36 | def is_json(json_str): 37 | try: 38 | json.loads(json_str) 39 | except Exception, e: 40 | return False 41 | return True 42 | 43 | def get_jsoninfo_dic(json_str): 44 | try: 45 | return json.loads(json_str) 46 | except Exception, e: 47 | return {} 48 | 49 | # GUI 50 | import os, sys 51 | from Tkinter import * 52 | import Tkinter, tkMessageBox 53 | from tkFileDialog import asksaveasfilename, askdirectory 54 | from collections import OrderedDict 55 | 56 | def wliu_Tk_Center(target_Tk): 57 | target_Tk.update() 58 | curWidth = target_Tk.winfo_reqwidth() 59 | curHeight = target_Tk.winfo_height() 60 | scnWidth,scnHeight = target_Tk.maxsize() 61 | tmpcnf = '%dx%d+%d+%d'%(curWidth,curHeight,(scnWidth-curWidth)/2,(scnHeight-curHeight)/2) 62 | target_Tk.geometry(tmpcnf) 63 | 64 | base_model_str = 'BaseModel' 65 | class JsonNode_InputBox(Frame): 66 | """docstring for JsonNode_InputBox""" 67 | def __init__(self, json_od, master=None): 68 | Frame.__init__(self, master) 69 | reload(sys) 70 | sys.setdefaultencoding('utf-8') 71 | self.pack() 72 | self.propertiesDict = {base_model_str : base_model_str} 73 | self.json_od = json_od 74 | self.config_exchange_info() 75 | self.createWidgets() 76 | 77 | def createWidgets(self): 78 | self.od_tuple = self.ex_od.popitem(last=True) 79 | self.label = Label(self, text=self.od_tuple[1]) 80 | self.label.pack() 81 | self.textfield = Entry(self, width=36) 82 | self.textfield.bind("", self.click_entercommend) 83 | self.textfield.pack() 84 | self.enter_btn = Button(self, text = 'Enter', command=self.click_enterhandler) 85 | self.enter_btn.pack() 86 | 87 | def click_entercommend(self, event): 88 | self.click_enterhandler() 89 | 90 | def click_enterhandler(self): 91 | save_key = self.od_tuple[0] 92 | text = self.textfield.get() 93 | self.propertiesDict[save_key] = text 94 | print '···%s<-config->%s complete' % (save_key, text) 95 | if len(self.ex_od) > 0: 96 | if len(self.ex_od) == 1: 97 | self.enter_btn['text'] = 'Out Put Files' 98 | self.od_tuple = self.ex_od.popitem(last=True) 99 | self.label['text'] = self.od_tuple[1] 100 | self.textfield.delete(0, END) 101 | else: 102 | self.outputFiles(self.json_od) 103 | self.showSuccess('转换成功!') 104 | self.quit() 105 | 106 | def config_exchange_info(self): 107 | self.ex_od = OrderedDict(self.get_exchange_list(self.json_od)) 108 | self.ex_od[base_model_str] = 'base model name' 109 | 110 | def get_exchange_list(self, json_OrderedDict): 111 | result_list = [] 112 | for key, value in json_OrderedDict.iteritems(): 113 | if isinstance(value, dict): 114 | title_tmp = '%s字段对应Class Name' % key 115 | result_list.append((key, title_tmp)) 116 | list_tmp = result_list 117 | result_list = self.get_exchange_list(value) + list_tmp 118 | elif isinstance(value, list): 119 | title_tmp = '%s字段对应数组的Member的Class Name' % key 120 | result_list.append((key, title_tmp)) 121 | if len(value) > 0: 122 | list_tmp = result_list 123 | result_list = self.get_exchange_list(value[0]) + list_tmp 124 | return result_list 125 | 126 | def get_propertyvalue(self, key): 127 | name = key 128 | try: 129 | name = self.propertiesDict[key] 130 | return name 131 | except Exception, e: 132 | return name 133 | 134 | def get_oderedlist_ocfiles_manager(self, json_OrderedDict, model_name): 135 | h_result_list = ['\n@interface %s : NSObject\n' % model_name] 136 | m_result_list = ['\n@implementation %s \n' % model_name] 137 | m_result_list.append('\n- (instancetype)initWith%sDic:(NSDictionary *)infoDic {\n\tself = [super init];\n\tif (self) {\n\t\tif (infoDic) {\n' % model_name) 138 | for key, value in json_OrderedDict.iteritems(): 139 | if isinstance(value, dict): 140 | name = self.get_propertyvalue(key) 141 | 142 | h_result_list.append('\n@property (nonnull, nonatomic, strong) %s *%s;%s\n' % (name ,key, '// %s' % value if wliu_desc else '')) 143 | m_result_list.append('\t\t\t_%s = [infoDic %sobjectForKey:@"%s"%s];\n' % (key, 'ks_' if ks_use else '', key, ' replace:@{}' if ks_use else '')) 144 | 145 | model_list_manager = self.get_oderedlist_ocfiles_manager(value, name) 146 | h_result_list.insert(0, model_list_manager.h_file_content) 147 | m_result_list.insert(0, model_list_manager.m_file_content) 148 | elif isinstance(value, list): 149 | if len(value) > 0: 150 | target_obj = value[0] 151 | if isinstance(target_obj, dict): 152 | name = self.get_propertyvalue(key) 153 | 154 | h_result_list.append('\n@property (nonnull, nonatomic, strong) NSArray<%s *> *%s;%s\n' % (name ,key, '// %s' % value if wliu_desc else '')) 155 | forin_str = 'NSMutableArray *resultArr = [@[] mutableCopy];\n\t\t\tNSArray *targetArr = [infoDic %sobjectForKey:@"%s"%s];\n\t\t\tfor (NSDictionary *dic in targetArr) {\n\t\t\t\t%s *obj = [[%s alloc] initWith%sDic:dic];\n\t\t\t\t[resultArr addObject:obj];\n\t\t\t}' % ('ks_' if ks_use else '', key, ' replace:@[]' if ks_use else '', name, name, name) 156 | m_result_list.append('\n\t\t\t%s\n\t\t\t_%s = %s;\n' % (forin_str, key, '[resultArr copy]')) 157 | 158 | model_list_manager = self.get_oderedlist_ocfiles_manager(target_obj, name) 159 | h_result_list.insert(0, model_list_manager.h_file_content) 160 | m_result_list.insert(0, model_list_manager.m_file_content) 161 | elif isinstance(target_obj, basestring): 162 | print 'str arr' 163 | elif isinstance(target_obj, (int, long)): 164 | print 'integer arr' 165 | elif isinstance(target_obj, float): 166 | print 'float arr' 167 | 168 | elif isinstance(value, basestring): 169 | h_result_list.append('\n@property (nonnull, nonatomic, copy) NSString *%s;%s\n' % (key, '// %s' % value if wliu_desc else '')) 170 | m_result_list.append('\t\t\t_%s = [infoDic %sobjectForKey:@"%s"%s];\n' % (key, 'ks_' if ks_use else '', key, ' replace:@""' if ks_use else '')) 171 | elif isinstance(value, (int, long)): 172 | h_result_list.append('\n@property (nonatomic, assign) NSInteger %s;%s\n' % (key, '// %d' % value if wliu_desc else '')) 173 | m_result_list.append('\t\t\t_%s = [[infoDic %sobjectForKey:@"%s"%s] integerValue];\n' % (key, 'ks_' if ks_use else '', key, ' replace:@0' if ks_use else '')) 174 | elif isinstance(value, float): 175 | h_result_list.append('\n@property (nonatomic, assign) float %s;%s\n' % (key, '// %f' % value if wliu_desc else '')) 176 | m_result_list.append('\t\t\t_%s = [[infoDic %sobjectForKey:@"%s"%s] floatValue];\n' % (key, 'ks_' if ks_use else '', key, ' replace:@0' if ks_use else '')) 177 | 178 | h_result_list.append('\n- (_Nonnull instancetype)initWith%sDic:(NSDictionary * _Nonnull)infoDic;\n\n@end\n' % model_name) 179 | m_result_list.append(('\n\t\t}\n\t}\n\treturn self;\n} \n\n@end\n\n\n')) 180 | oc_f = oc_files_manager(h_file_content=h_result_list, m_file_content=m_result_list) 181 | return oc_f 182 | 183 | def get_oderedstr(self, json_orderedlist): 184 | result_str = '' 185 | for x in json_orderedlist: 186 | if isinstance(x, basestring): 187 | result_str += x 188 | elif isinstance(x, list): 189 | strTmp = result_str 190 | result_str = strTmp + self.get_oderedstr(x) 191 | else: 192 | pass 193 | return result_str 194 | 195 | def outputFiles(self, json_od): 196 | oc_list_manager = self.get_oderedlist_ocfiles_manager(self.json_od, self.propertiesDict[base_model_str]) 197 | self.outputFile(self.get_oderedstr(oc_list_manager.h_file_content), '.h') 198 | self.outputFile(self.get_oderedstr(oc_list_manager.m_file_content),'.m') 199 | 200 | def outputFile(self, text, extension): 201 | options = {} 202 | options['initialfile'] = self.propertiesDict[base_model_str]+extension 203 | options['defaultextension'] = extension 204 | options['title'] = '%s file\'s name' % extension 205 | 206 | filename = asksaveasfilename(**options) 207 | if filename: 208 | if len(text) > 0: 209 | f1 = open(filename, 'w') 210 | if extension == '.h': 211 | prefix_str = '/*!\n *\tproducted by oc_json_plugin.py\n *\tauth: w6\n*/\n%s\n' % '#import ' 212 | elif extension == '.m': 213 | header_str = '' 214 | try: 215 | header_str = os.path.split(filename)[-1].split('.')[0]+'.h' 216 | self.savename = os.path.split(filename)[-1].split('.')[0] 217 | except Exception, e: 218 | pass 219 | prefix_str = '/*!\n *\tproducted by oc_json_plugin.py\n *\tauth: w6\n */\n#import "%s"\n' % header_str 220 | f1.write(prefix_str+text) 221 | f1.close() 222 | if extension == '.m': 223 | self.savepath = os.path.split(filename)[0] 224 | 225 | def showSuccess(self, msg): 226 | try: 227 | tkMessageBox.showinfo('Alert!', msg+'文件名为'+self.savename) 228 | os.system('open %s' % self.savepath) 229 | except Exception, e: 230 | print '你放弃了保存' 231 | 232 | 233 | class Appliction(Frame): 234 | """docstring for Appliction""" 235 | def __init__(self, master=None): 236 | Frame.__init__(self, master) 237 | reload(sys) 238 | sys.setdefaultencoding('utf-8') 239 | self.pack() 240 | self.createWidgets() 241 | 242 | def createWidgets(self): 243 | self.inputTextView = Text(self, width=166, height=36) 244 | self.inputTextView.bind("", self.selectText) 245 | self.inputTextView.bind("", self.onPaste) 246 | self.inputTextView.bind("", self.onCut) 247 | self.inputTextView.bind("", self.onCopy) 248 | self.inputTextView.pack(expand=0) 249 | self.checkBtn = Button(self, text = 'Exchange Json Node', command=self.pack_jsonnode_window) 250 | self.checkBtn.pack() 251 | 252 | def get_ordereddic(self, json_dic): 253 | obj_list = [] 254 | objs_list = [] 255 | properties_list = [] 256 | for key, value in json_dic.iteritems(): 257 | if isinstance(value, dict): 258 | obj_list.append((key, self.get_ordereddic(value))) 259 | elif isinstance(value, list): 260 | objs_list.append((key, value)) 261 | elif isinstance(value, basestring): 262 | properties_list.append((key, value)) 263 | elif isinstance(value, (int, long)): 264 | properties_list.append((key, value)) 265 | elif isinstance(value, float): 266 | properties_list.append((key, value)) 267 | 268 | od = OrderedDict(obj_list + objs_list + properties_list) 269 | return od 270 | 271 | def pack_jsonnode_window(self): 272 | alltext = self.inputTextView.get(1.0, END+'-1c') 273 | if is_json(alltext) == False: 274 | self.showAlert('输入的是非法json') 275 | return 276 | info_dic = get_jsoninfo_dic(alltext) 277 | tmp_top = Toplevel() 278 | tmp_top.title('Exchange Window') 279 | tmp_top.wm_attributes("-topmost", 1) 280 | jn_ib = JsonNode_InputBox(self.get_ordereddic(info_dic), tmp_top) 281 | wliu_Tk_Center(tmp_top) 282 | jn_ib.pack() 283 | 284 | def selectText(self, event): 285 | self.inputTextView.tag_add(Tkinter.SEL, '1.0', Tkinter.END) 286 | return 'break'; 287 | 288 | def onPaste(self, event): 289 | try: 290 | self.selection_get(selection='CLIPBOARD') 291 | except TclError: 292 | pass 293 | 294 | def onCut(self, event): 295 | self.onCopy(event) 296 | try: 297 | self.inputTextView.delete(SEL_FIRST, SEL_LAST) 298 | except Exception, e: 299 | pass 300 | 301 | def onCopy(self, event): 302 | try: 303 | text = self.inputTextView.get(SEL_FIRST, SEL_LAST) 304 | self.clipboard_clear() 305 | self.clipboard_append(text) 306 | except Exception, e: 307 | pass 308 | 309 | def showAlert(self, msg): 310 | tkMessageBox.showinfo('Waring!', msg) 311 | 312 | root = Tk(className='Objective Json Plugin') 313 | app = Appliction(root) 314 | wliu_Tk_Center(root) 315 | app.mainloop() 316 | 317 | try: 318 | root.destroy() 319 | except Exception, e: 320 | pass 321 | 322 | --------------------------------------------------------------------------------