How to assign a JSON array to another JSON array in Objective-C

54 Views Asked by At

I have two JSON objects and they are:

{
    "list1": [{
        "innerList": [{
            "innerListItem1": 50,
            "innerListItem2": 23,
            "innerListItem3": false,
            "innerListItem4": 43,
            "innerListItem5": 74
        }, {
            "innerListItem1": 22,
            "innerListItem2": 31,
            "innerListItem3": 90,
            "innerListItem4": 11,
            "innerListItem5": 27
        }]
    }]
}
{
    "innerList2": [{
        "innerList2Item1": 32,
        "innerList2Item2": 66,
        "innerList2Item3": 93,
        "innerList2Item4": 28,
        "innerList2Item5": true
    }, {
        "innerList2Item1": 23,
        "innerList2Item2": 94,
        "innerList2Item3": 6,
        "innerList2Item4": 0,
        "innerList2Item5": 18
    }]
}

I want to replace innerList with innerList2 using Objective-C and my code:

// here, I'm fetching a JSON object from user defaults and this is my list1
NSString *list1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"list1"];

// and here, I'm reading a JSON object from a JSON file and, above and this code works fine. I can read the both JSON objects.
NSString *list2 = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

// what I tried to access and assign the innerList2
NSString *oldList = [list1 valueForKeyPath:@"innerList"];
oldList = list2

but Xcode throws this exception at the runtime:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x2839cd350> valueForUndefinedKey:]: this class is not key value coding-compliant for the key list1.'
*** First throw call stack:
(0x1fdf96180 0x1fd16e9f8 0x1fdeb3604 0x1fe97f3ac 0x1fe8f38cc 0x1003b6d14 0x100655c10 0x100655be8 0x100690aac 0x100655c34 0x1040e9460 0x1040ed01c 0x1040eabd0 0x1040eac18 0x1040eafb8 0x1040ea3bc 0x1040ecf34 0x1040ece3c 0x1040ed444 0x100691664 0x1006916b4 0x1040f8b18 0x1040f826c 0x1040f8118 0x1040f81e0 0x1040f91a0 0x22b48023c 0x1040f7f58 0x1040f8290 0x1040ed424 0x1040eb428 0x1040ea3bc 0x1040ecf34 0x1040ece3c 0x100499f3c 0x1004cd124 0x1004ccb98 0x1004cc53c 0x1004cc594 0x229c5ba20 0x229c5e354 0x229c5c9c0 0x22a20b1b8 0x22a1f9bfc 0x22a218868 0x1fdf27d6c 0x1fdf27670 0x1fdf226d4 0x1fdf21fb4 0x20012379c 0x22a1ffc38 0x100420a14 0x1fd9e58e0)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

I've Googled the exception but the questions and the answers are mostly related to XIB.
My questions are what is the root cause of this exception and how can I assign the list?

0

There are 0 best solutions below