JLChen
2021-11-04 1443556e9ccb1a19ed8e6710c16c8adc4d4f4fb3
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
//
//  Copyright © 2017年 Zhejiang Dahua Technology Co.,Ltd. All rights reserved.
//
 
#import "NSObject+JSON.h"
 
@implementation NSObject (JSON)
 
- (NSString *)dh_jsonString
{
    if (![NSJSONSerialization isValidJSONObject:self]) {
        NSLog(@"❌❌ Error: Invalid json object");
        return nil;
    }
    NSError *error;
    NSData *data = [NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
    NSString *jsonData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return jsonData;
}
 
@end
 
 
 
@implementation NSString (JSON)
 
- (id)dh_jsonObject
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    return result;
}
 
- (NSDictionary *)dh_jsonDictionary
{
    id result = [self dh_jsonObject];
    if ([result isKindOfClass:[NSDictionary class]]) {
        return (NSDictionary *)result;
    }
    
    return nil;
}
 
- (NSArray *)dh_jsonArray
{
    id result = [self dh_jsonObject];
    if ([result isKindOfClass:[NSArray class]]) {
        return (NSArray *)result;
    }
    
    return nil;
}
@end