Get values from JSON string - Objective C

15,107

Solution 1

This JSON should result in a Dictionary

NSDictionary *jsonDict = [responseString JSONValue];

then use:

[jsonDict objectForKey:@"d"];

Solution 2

When you can afford to require iOS 5 you should try NSJSONSerialization.

Your code could look like this but I suggest reading the Docs first.

    NSArray* jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:someError]

Solution 3

Try using the SBJasonParser library for iOS.

You can then use this code (for all iOS versions):

SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
NSDictionary* myDict = [parser objectWithString: responseString];

Note: Your code above has a JSON Dictionary but you were trying to access it as an Array.

Share:
15,107
roof
Author by

roof

Updated on July 23, 2022

Comments

  • roof
    roof almost 2 years

    I have this JSON response string:

    {"d":"{\"ID_usuario\":\"000130\",\"Nombre\":null,\"Vipxlo\":0,\"Provmun\":null,\"Descuentos\":null,\"Listaviplocal\":null}"}`
    

    With this code:

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection 
    {
        //Check valid signal
    
        connection = nil;
    
        NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        //data =nil;
    
        NSArray *jsonArray = [responseString JSONValue];
    

    How can I do it?

  • roof
    roof about 12 years
    Hi I've added NSString *userName = [result objectForKey:@"Nombre"]; but I've got "variable is not a CFString at this time" value for userName. Do you why is it? Thanks for your help.
  • iDroid
    iDroid about 12 years
    NSJsonSerializattion is the best and optimized solution compared to anyother framework.But here i found the pretty good solution for identifying the best among SBJson and NSJSONSerialization (Before the release of ios5.0 SBJSON is the good framework for handling Json objects).
  • sensorario
    sensorario over 11 years
    I'm sorry but, ... I dont have any JSONValue class. Can someone suggest me how to get this class?
  • vikingosegundo
    vikingosegundo over 11 years
    @SimoneDemoGentili See cortez' answer. OP uses a third party tool, that isnt needed for iOS 5+.
  • sensorario
    sensorario over 11 years
    Where I can find this third party tool?