4

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.

RickiG
  • 11,380
  • 13
  • 81
  • 120

2 Answers2

2

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]];
Won
  • 1,795
  • 2
  • 12
  • 22
0

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.

NWCoder
  • 5,296
  • 1
  • 26
  • 23
  • Hi Peter and NWCoder. My overall NSDictionary I cast to mutable when parsing is complete. The problem is then the 'user' and 'object' dictionaries inside the overall dictionary are still imutable:( For now I go through each of my json dictionaries, make the outer dict mutable, pull out the inner dicts by key, make a mutable copy of them, delete the old dict and reinsert the new mutable one - terrible workflow, especially when objects change server side. The casting, mutable copy or fast initializer only seem to work on the outer dictionary, which is understandable I guess. – RickiG Mar 10 '11 at 12:42