Have TouchJSON return mutable objects?

2019-04-09 14:28发布

I am receiving some json from a web service. I parse this using the TouchJSON library. I keep the data around for the user to change certain values and then I want to return it to the web service.

The JSON object I get contains NSDictionary Objects within the object, like this:

[
    {
        "id": null,
        "created_at": 12332343,
        "object": {
            "name": "Some name",
            "age" : 30 
        },
        "scope": "it stuff",
        "kind_id": 1,
        "valid": true,
        "refering_statement": {
            "id": 95 
        },
        "user": {
            "id": 1 
        } 
    }
]

If I want to change values in this dictionary, I can't because the returned objects from TouchJSON are not mutable.

Is there a way to have have TouchJSON return mutable objects?

or is there a way to have Objective C make an NSDictionary and all its children mutable?

or do I have to just go through every NSDictionary in NSDictionary and copy all data into a mutable copy and then reinsert everything?

Hope someone can help me out on this one:) thanks in advance.

2条回答
SAY GOODBYE
2楼-- · 2019-04-09 15:08

You can create a mutable dictionary from a dictionary like this.

(assuming your json parsed dictionary was named jsonDictionary)

NSMutableDictionary *userDictionary = [NSMutableDictionary dictionaryWithDictionary:jsonDictionary];

Hope that solves it for you.

查看更多
虎瘦雄心在
3楼-- · 2019-04-09 15:15

TouchJson has an option to return mutable object rather than normal. (I found it by looking at source code.) Default is to return its "copy", not "mutablecopy".

NSError *error = nil;    
jsonString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];
CJSONDeserializer *jsondeserializer = [CJSONDeserializer deserializer];
jsondeserializer.scanner.options = kJSONScannerOptions_MutableContainers;
NSMutableDictionary *jsonitems = [[NSMutableDictionary alloc] initWithDictionary:[jsondeserializer deserializeAsDictionary:jsonData error:&error]];
查看更多
登录 后发表回答