Parsing JSON string to a NSMutableArray

2019-08-28 17:43发布

问题:

This is my string:

[{"id":"1","nome":"Adriatik"},{"id":"2","nome":"Ard"},{"id":"3","nome":"Albana"},{"id":"4","nome":"Adriana"}]

I would like to parse all 'name' of the JSON string into a NSMutableArray.

Sorry for my english!

回答1:

Whenever I have to handle some JSON code, the first thing I like to do is create a class based on the JSON text. So, for example if your JSON is representing a U.S. state, create a "State" class.

There's a cool little product that you can use for this. It's called Objectify and costs about $15. No doubt people can advise on other free stuff that might do something similar.

For the actual Json parsing, I use SBJson. There's quite a few Json parsing frameworks out there for Objective-C so definitely have a look around to see what takes your fancy.

Next, with SBJson, do the actual parsing:

-(NSDictionary *)parseJsonFromUrl
{
    NSAssert(mUrl, @"Must set a url before invoking %@", __PRETTY_FUNCTION__);

    // Create new SBJSON parser object
    SBJsonParser *parser = [[SBJsonParser alloc] init];

    // Prepare URL request to download JSON
    NSURLRequest *request = [NSURLRequest requestWithURL:mUrl];

    // Perform request and get JSON back as a NSData object
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    // Get JSON as a NSString from NSData response
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

    // parse the JSON response into an object
    // Here we're using NSArray since we're parsing an array of JSON status objects
    return [parser objectWithString:json_string error:nil];
}

That returns a NSDictionary. You know have to look through that dictionary to set the values of your model class. Here's how to do that whilst at the same time loading the values into the NSMutableArray:

-(void)downloadJsonData
{    
    NSDictionary *statesDict = [self parseJsonFromUrl];

    NSMutableArray *statesArray = [NSMutableArray arrayWithCapacity:[statesDict count]];

    for (NSDictionary *stateDict in stateDict)
    {
        State *aState = [[[State alloc] init] autorelease];
        aState.stateId = [stateDict valueForKey:@"id"];
        aState.name = [stateDict valueForKey:@"name"];

        [statesArray addObject:aState];
    }
}

Note that I use a property name of stateId not id so as not to clash with the Objective-C object pointer type.



回答2:

Use SBJson classes and call -JSONValue method

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
   // NSLog(@" Response String %@", responseString);
    //converted response json string to a simple NSdictionary


    NSMutableArray *results = [responseString JSONValue];