forked from NianJi/formatJSON
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSString+FormatJSON.m
More file actions
99 lines (87 loc) · 2.96 KB
/
NSString+FormatJSON.m
File metadata and controls
99 lines (87 loc) · 2.96 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
//
// NSString+FormatJSON.m
// SuningEBuy
//
// Created by liukun on 13-2-18.
// Copyright (c) 2013年 BlueBox. All rights reserved.
//
#import "NSString+FormatJSON.h"
@implementation NSString (FormatJSON)
- (NSString *)formatJSON
{
int indentLevel = 0;
BOOL inString = NO;
char currentChar = '\0';
char *tab = " ";
NSUInteger len = [self lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
const char *utf8 = [self UTF8String];
NSMutableData *buf = [NSMutableData dataWithCapacity:(NSUInteger)(len * 1.1f)];
for (int i = 0; i < len; i++)
{
currentChar = utf8[i];
switch (currentChar) {
case '{':
case '[':
if (!inString) {
[buf appendBytes:¤tChar length:1];
[buf appendBytes:"\n" length:1];
for (int j = 0; j < indentLevel+1; j++) {
[buf appendBytes:tab length:strlen(tab)];
}
indentLevel += 1;
} else {
[buf appendBytes:¤tChar length:1];
}
break;
case '}':
case ']':
if (!inString) {
indentLevel -= 1;
[buf appendBytes:"\n" length:1];
for (int j = 0; j < indentLevel; j++) {
[buf appendBytes:tab length:strlen(tab)];
}
[buf appendBytes:¤tChar length:1];
} else {
[buf appendBytes:¤tChar length:1];
}
break;
case ',':
if (!inString) {
[buf appendBytes:",\n" length:2];
for (int j = 0; j < indentLevel; j++) {
[buf appendBytes:tab length:strlen(tab)];
}
} else {
[buf appendBytes:¤tChar length:1];
}
break;
case ':':
if (!inString) {
[buf appendBytes:":" length:1];
} else {
[buf appendBytes:¤tChar length:1];
}
break;
case ' ':
case '\n':
case '\t':
if (inString) {
[buf appendBytes:¤tChar length:1];
}
break;
case '"':
if (i > 0 && utf8[i-1] != '\\')
{
inString = !inString;
}
[buf appendBytes:¤tChar length:1];
break;
default:
[buf appendBytes:¤tChar length:1];
break;
}
}
return [[[NSString alloc] initWithData:buf encoding:NSUTF8StringEncoding] autorelease];
}
@end