-
Notifications
You must be signed in to change notification settings - Fork 351
Expand file tree
/
Copy pathESInputJsonController.m
More file actions
452 lines (331 loc) · 15.1 KB
/
Copy pathESInputJsonController.m
File metadata and controls
452 lines (331 loc) · 15.1 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//
// TestWindowController.m
// ESJsonFormat
//
// Created by 尹桥印 on 15/6/19.
// Copyright (c) 2015年 EnjoySR. All rights reserved.
//
#import "ESInputJsonController.h"
#import "ESDialogController.h"
#import "ESJsonFormatManager.h"
#import "ESJsonFormat.h"
@interface ESInputJsonController ()<NSTextViewDelegate,NSWindowDelegate>
@property (nonatomic, strong) NSMutableDictionary *replaceClassNames;
@property (unsafe_unretained) IBOutlet NSTextView *inputTextView;
@property (weak) IBOutlet NSButton *enterButton;
@property (weak) IBOutlet NSButton *cancelButton;
@property (weak) IBOutlet NSScrollView *scrollView;
@property (weak) IBOutlet NSButton *createNewFileCheckBtn;
@end
@implementation ESInputJsonController
-(NSMutableDictionary *)replaceClassNames{
if (!_replaceClassNames) {
_replaceClassNames = [NSMutableDictionary dictionary];
}
return _replaceClassNames;
}
- (void)windowDidLoad {
[super windowDidLoad];
self.inputTextView.delegate = self;
self.window.delegate = self;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewValueChanged:) name:NSTextViewDidChangeSelectionNotification object:nil];
}
-(void)windowWillClose:(NSNotification *)notification{
if ([self.delegate respondsToSelector:@selector(windowWillClose)]) {
[self.delegate windowWillClose];
}
}
- (IBAction)cancelButtonClick:(NSButton *)sender {
[self close];
}
- (IBAction)enterButtonClick:(NSButton *)sender {
NSTextView *textView = self.inputTextView;
id result = [self dictionaryWithJsonStr:textView.string];
if ([result isKindOfClass:[NSError class]]) {
NSError *error = result;
NSAlert *alert = [NSAlert alertWithError:error];
[alert runModal];
NSLog(@"Error:Json is invalid");
}else{
NSDictionary *dic = [self dealNameWithDictionary:result];
[self close];
ESJsonFormatManager *engine = [[ESJsonFormatManager alloc] initWithCreateToFile:NO];
engine.replaceClassNames = [NSDictionary dictionaryWithDictionary:self.replaceClassNames];
self.replaceClassNames = nil;
ESFormatInfo *info = nil;
if ([ESJsonFormat instance].isSwift) {
info = [engine parseSwiftWithDic:dic];
}else{
info = [engine parseObjcWithDic:dic];
}
[[NSNotificationCenter defaultCenter] postNotificationName:ESFormatResultNotification object:info];
}
}
/**
* Set class name
*/
-(NSDictionary *)dealNameWithDictionary:(id)datas{
if ([datas isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:datas];
[dic enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSArray class]] || [obj isKindOfClass:[NSDictionary class]]) {
ESDialogController *dialog = [[ESDialogController alloc] initWithWindowNibName:@"ESDialogController"];
NSString *msg = [NSString stringWithFormat:@"The '%@' child items class name is:",key];
if ([obj isKindOfClass:[NSDictionary class]]) {
msg = [NSString stringWithFormat:@"The '%@' correspond class name is:",key];
}
[dialog setDataWithMsg:msg defaultClassName:[key capitalizedString] useDefault:nil enter:^(NSString *className) {
if (![className isEqualToString:key]) {
self.replaceClassNames[key] = className;
}
}];
[NSApp beginSheet:[dialog window] modalForWindow:[NSApp mainWindow] modalDelegate:nil didEndSelector:nil contextInfo:nil];
[NSApp runModalForWindow:[dialog window]];
if ([obj isKindOfClass:[NSDictionary class]]) {
[dic setObject:[self dealNameWithDictionary:obj] forKey:key];
}
}
}];
return dic;
}else if([datas isKindOfClass:[NSArray class]]){
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
ESDialogController *dialog = [[ESDialogController alloc] initWithWindowNibName:@"ESDialogController"];
NSString *msg = [NSString stringWithFormat:@"The json is an array,root class name is:"];
[dialog setDataWithMsg:msg defaultClassName:@"ESModal" useDefault:nil enter:^(NSString *className) {
NSString *lowerStr = [className lowercaseString];
dic[lowerStr] = datas;
self.replaceClassNames[lowerStr] = className;
}];
[NSApp beginSheet:[dialog window] modalForWindow:[NSApp mainWindow] modalDelegate:nil didEndSelector:nil contextInfo:nil];
[NSApp runModalForWindow:[dialog window]];
return dic;
}
return nil;
}
-(void)close{
[super close];
}
-(void)textDidChange:(NSNotification *)notification{
NSTextView *textView = notification.object;
self.createNewFileCheckBtn.hidden = YES;
id result = [self dictionaryWithJsonStr:textView.string];
if ([result isKindOfClass:[NSDictionary class]]) {
NSDictionary *dic = result;
[dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSArray class]]) {
self.createNewFileCheckBtn.hidden = YES;
*stop = YES;
}
}];
}
}
- (void)textViewValueChanged:(NSNotification *)noti
{
if ([noti.object isKindOfClass:[NSTextView class]]) {
self.inputTextView.textColor = [NSColor redColor];
}
}
/**
* 检查是否是一个有效的JSON
*/
-(id)dictionaryWithJsonStr:(NSString *)jsonString{
//如果是字典description的一部分, 直接截获
id dicOrArray;
dicOrArray = [self dictionaryWithString:jsonString];
if (dicOrArray) {
return dicOrArray;
}
//以JSON字符串的解析
jsonString = [[jsonString stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"jsonString=%@",jsonString);
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
dicOrArray = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err] : nil;
if (err) {
return err;
}else{
return dicOrArray;
}
}
/**多级字典*/
- (NSDictionary *)dictionaryWithString:(NSString *)string
{
NSArray *arrayData = [string componentsSeparatedByString:@"="];
if ([arrayData.firstObject isEqualToString:@""] || [arrayData.lastObject isEqualToString:@""]) {
return nil;
}
string = [string stringByReplacingOccurrencesOfString:@"(" withString:@"["];
string = [string stringByReplacingOccurrencesOfString:@")" withString:@"]"];
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@""];
NSString *firstChar = [string substringToIndex:1];
NSString *lastChar = [string substringFromIndex:string.length - 1];
//如果没有字典符号, 补上
if (![firstChar isEqualToString:@"{"]) {
string = [NSString stringWithFormat:@"{\n%@", string];
}
if (![lastChar isEqualToString:@"}"]) {
string = [NSString stringWithFormat:@"%@\n}", string];
}
NSArray *array = [string componentsSeparatedByString:@"\n"];
//重组每行内容
NSMutableArray *mutableArrayRowChars = [NSMutableArray array];
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//去除每一行中的 ;
obj = [obj stringByReplacingOccurrencesOfString:@";" withString:@""];
//筛选键值行 带等号的
if ([obj rangeOfString:@"="].location != NSNotFound) {
//重组key 前后加爽引号
NSString *key = [obj componentsSeparatedByString:@"="].firstObject;
key = [NSString stringWithFormat:@"%@%@%@", @"\"", key, @"\""];
NSString *value = [obj componentsSeparatedByString:@"="].lastObject;
//筛出字典 数组
BOOL isValue = !([value hasSuffix:@"{"] || [value hasSuffix:@"["]);
if (isValue) {
//重新组合字典key
value = [self restructuringString:value];
}
//重组键值
obj = [NSString stringWithFormat:@"%@:%@", key, value];
}
//筛选数组行, 仅是字符串或数字的
else if (![obj containsString:@"["] && ![obj containsString:@"]"] && ![obj containsString:@"{"] && ![obj containsString:@"}"]) {
//重新组合 数组值 记录是否包含分号, 如果有, 先移除再补上
if ([obj length] > 0) { // 去掉长度为0的
BOOL haveSemicolon = [[obj substringFromIndex:[obj length] - 1] containsString:@","];
if (haveSemicolon) {
obj = [obj stringByReplacingOccurrencesOfString:@"," withString:@""];
}
obj = [self restructuringString:obj];
if (haveSemicolon) {
obj = [obj stringByAppendingFormat:@"%@", @","];
}
}
}
[mutableArrayRowChars addObject:obj];
}];
//重组每行内容 在该有的位置添加分号
NSMutableArray *mutableArrayRowChars2 = [NSMutableArray array];
[mutableArrayRowChars enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//筛选正常的行 通过 ": [ {
if ([obj rangeOfString:@"\":"].location != NSNotFound && ![obj hasSuffix:@"["] && ![obj hasSuffix:@"{"]) {
//遇到下一行是 } 直接追加 ,
if ((idx + 1) < mutableArrayRowChars.count && ![mutableArrayRowChars[idx + 1] hasPrefix:@"}"]) {
obj = [obj stringByAppendingFormat:@"%@", @","];
}
}
//末尾是} ] 时, 追加 ,
else if ([obj hasSuffix:@"]"] || [obj hasSuffix:@"}"]){
//排除当前行是} 并且下一行是 ] 并且 不是最后一行的情况
if ([obj hasSuffix:@"}"] && (idx + 1) < mutableArrayRowChars.count && [mutableArrayRowChars[idx + 1] hasSuffix:@"]"]) {
}else {
obj = [obj stringByAppendingFormat:@"%@", @","];
}
}
//移除最后一行 } 后面的 ,
if (idx == mutableArrayRowChars.count - 1) {
obj = [obj stringByReplacingOccurrencesOfString:@"," withString:@""];
}
[mutableArrayRowChars2 addObject:obj];
}];
NSString *stringJSON = [mutableArrayRowChars2 componentsJoinedByString:@"\n"];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[stringJSON dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:NULL];
return dictionary;
}
///**一级数字典*/
//- (NSDictionary *)dictionaryWithString:(NSString *)string
//{
//
// string = [string stringByReplacingOccurrencesOfString:@"{" withString:@""];
// string = [string stringByReplacingOccurrencesOfString:@"}" withString:@""];
//
// string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
// string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@""];
// string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//
//
// NSArray *array = [string componentsSeparatedByString:@";"];
// NSMutableArray *mutableArray = [NSMutableArray array];
//
// [array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
// id key = [obj componentsSeparatedByString:@"="].firstObject;
// id value = [obj componentsSeparatedByString:@"="].lastObject;
//
// if ([self validateNum:value]) {
//
// //重新赋值, 避免前面是 一串0
// if ([value rangeOfString:@"."].location != NSNotFound) {
// value = [@([value floatValue]) stringValue];
// }else {
// value = [@([value integerValue]) stringValue];
// }
//
// }else {
// value = [NSString stringWithFormat:@"%@%@%@", @"\"", @"=====", @"\""];
// }
//
// if (![key isEqualToString:@""]) {
// key = [NSString stringWithFormat:@"%@%@%@", @"\"", key, @"\""];
// [mutableArray addObject:[NSString stringWithFormat:@"%@:%@", key, value]];
// }
//
//
// }];
//
//
// NSString *stringJSON = [mutableArray componentsJoinedByString:@","];
// stringJSON = [NSString stringWithFormat:@"{%@}", stringJSON];
//
// NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[stringJSON dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:NULL];
//
// return dictionary;
//}
/**验证整数*/
- (BOOL)validateInteger:(NSString *)candidate;
{
if ([candidate isEqualToString:@""]) {
return NO;
}
NSString *regex = @"^-?[1-9]/d*$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
return [predicate evaluateWithObject:candidate];
}
/**验证浮点数*/
- (BOOL)validateFloat:(NSString *)candidate;
{
if ([candidate isEqualToString:@""]) {
return NO;
}
NSString *regex = @"^(-?\\d+)(\\.\\d+)?$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
return [predicate evaluateWithObject:candidate];
}
/**重组字符串, 在字符串前后添加双引号*/
- (NSString *)restructuringString:(NSString *)string;
{
if ([self validateInteger:string] || [self validateFloat:string]) {
//长度过长, 直接转为字符串
if ([string componentsSeparatedByString:@"."].firstObject.length > 8) {
string = [NSString stringWithFormat:@"%@%@%@", @"\"", @"字符串的值", @"\""];
}
else {
//重新赋值, 避免前面是 一串0
if ([string rangeOfString:@"."].location != NSNotFound) {
string = [@([string floatValue]) stringValue];
//如果转换后没有小数点
if ([string rangeOfString:@"."].location == NSNotFound) {
string = [string stringByAppendingString:@".88"];
}
}else {
string = [@([string integerValue]) stringValue];
}
}
}else {
//重组value 前后加双引号
string = [NSString stringWithFormat:@"%@%@%@", @"\"", @"字符串的值", @"\""];
}
return string;
}
@end