This repository has been archived by the owner on Apr 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
NSDictionary+BSJSONAdditions.m
67 lines (59 loc) · 2.17 KB
/
NSDictionary+BSJSONAdditions.m
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
//
// BSJSONAdditions
//
// Created by Blake Seely on 2/1/06.
// Copyright 2006 Blake Seely - http://www.blakeseely.com All rights reserved.
// Permission to use this code:
//
// Feel free to use this code in your software, either as-is or
// in a modified form. Either way, please include a credit in
// your software's "About" box or similar, mentioning at least
// my name (Blake Seely).
//
// Permission to redistribute this code:
//
// You can redistribute this code, as long as you keep these
// comments. You can also redistribute modified versions of the
// code, as long as you add comments to say that you've made
// modifications (keeping these original comments too).
//
// If you do use or redistribute this code, an email would be
// appreciated, just to let me know that people are finding my
// code useful. You can reach me at [email protected]
#import "NSDictionary+BSJSONAdditions.h"
#import "NSScanner+BSJSONAdditions.h"
#import "NSString+BSJSONAdditions.h"
#import "BSJSONEncoder.h"
@implementation NSDictionary (BSJSONAdditions)
+ (NSDictionary *)dictionaryWithJSONString:(NSString *)jsonString
{
NSScanner *scanner = [[NSScanner alloc] initWithString:jsonString];
NSDictionary *dictionary = nil;
[scanner scanJSONObject:&dictionary];
[scanner release];
return dictionary;
}
- (NSString *)jsonStringValue
{
return [self jsonStringValueWithIndentLevel:0];
}
- (NSString *)jsonStringValueWithIndentLevel:(NSInteger)level
{
NSMutableString *jsonString = [[NSMutableString alloc] initWithString:jsonObjectStartString];
BOOL first = YES;
NSString *valueString;
for (NSString *keyString in self) {
valueString = [BSJSONEncoder jsonStringForValue:[self objectForKey:keyString] withIndentLevel:level];
if (!first) {
[jsonString appendString:jsonValueSeparatorString];
}
if (level != jsonDoNotIndent) { // indent before each key
[jsonString appendString:[NSString jsonIndentStringForLevel:level]];
}
[jsonString appendFormat:@" %@ %@ %@", [keyString jsonStringValue], jsonKeyValueSeparatorString, valueString];
first = NO;
}
[jsonString appendString:jsonObjectEndString];
return [jsonString autorelease];
}
@end