将对象的嵌套数组保存到 JSON

问题描述 投票:0回答:1

我有一个嵌套对象数组,我想将其保存为 JSON。对象定义如下:

@interface TreeNode : NSObject

@property(nonatomic, strong) NSString *title;
@property(nonatomic, strong) NSMutableArray<TreeNode *> *children;
@property(nonatomic, strong) NSString *identifier;
@property(nonatomic, assign) bool isCompleted;

- (instancetype)initWithValue:(NSString *)title :(NSString *)number;
- (void)addChild:(TreeNode *)child;

@end

@implementation TreeNode

- (instancetype)initWithValue:(NSString *)title :(NSString *)number {
    self = [super init];
    if (self) {
        _isCompleted = false;
        _title = [title copy];
        _identifier = [number copy];
        _children = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)addChild:(TreeNode *)child {
    [_children addObject:child];
}

- (void)dealloc
{
    [_title release];
    [_identifier release];
    [_children release];
    
    [super dealloc];
}

@end

上述对象作为无限嵌套对象添加到数组中,如下所示: [[字符串,[[字符串,[]],[字符串,[]]]],[字符串,[]],[字符串,[]]] 上面的 [String,[]] 代表我的类对象(TreeNode)。 我想将其保存在本地文档目录中。我正在尝试将其另存为 JSON,但无法将其转换为 JSON 对象。

json objective-c
1个回答
0
投票

我可以将数组保存如下:

    -(void) saveToDoList:(NSMutableArray<TreeNode *> *)todoList {
    NSMutableArray *array = [self convertArrayToJson:todoList];
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease];
    [self writeStringToFile:jsonString];
}

-(NSMutableArray *) convertArrayToJson: (NSMutableArray *) array {
    NSMutableArray *mainArray = [NSMutableArray new];
    
    for (TreeNode *element in array) {
        NSMutableDictionary *node = [NSMutableDictionary new];
        [node setValue:element.title forKey:keyTitle];
        [node setValue:element.identifier forKey:keyIdentifier];
        
        if (element.children != nil && [[element children] count] > 0) {
            NSMutableArray *array1 = [self convertArrayToJson:element.children];
            [node setValue:array1 forKey:keyChildren];
        } else {
            [node setValue:nil forKey:keyChildren];
        }
        [mainArray addObject:node];
    }
    return mainArray;
}

- (void)writeStringToFile:(NSString*)aString {
    NSString *fileAtPath = [self jsonFilePath];
    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
        [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
    }
    [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
© www.soinside.com 2019 - 2024. All rights reserved.