0

I have a json feed like this:

 {
result = {
  cars =  {
        brand = {
             fields = {
       name = {
        id = 1234;
                        value = "Opel Astra";
           };
     description = {
        id = 4432;
        value = "Some description"; 
    };
           };
      fields = {
       name = {
        id = 1453;
                        value = "Opel Omega";
           };
     description = {
        id = 4430;
        value = "Some description"; 
    };
    ...
           };
     };
   };

When I parse this, I get all objects in an array and not as a seperate string which is what I want.

I've done like this:

NSArray *result = [[res objectForKey:@"result"]valueForKeyPath:@"cars.brand.fields.name.value"];
NSLog(@"%@" , [result objectAtIndex:0]):

The output is:

(
    "Opel Astra",
    "Opel Omega",
    ....
),

How can I achieve getting one string at a time, instead of an array containing a lot of string?

Thanks!

Magnus
  • 1,444
  • 5
  • 22
  • 31

4 Answers4

1

Try SBJSON to parse the JSON in objective-C.

You can get the SBJSON from here

nithinbhaktha
  • 723
  • 5
  • 8
0

Use NSJSONSerialization to retrieve the JSON data into a foundation object.

See also this post.

Community
  • 1
  • 1
petert
  • 6,672
  • 3
  • 38
  • 46
0

You are also able to Handle the JSON String as id-Value. Then you call [jsonString objectForKey:@"result"].

And try this Function, it works perfectly for me ;)

- (id) objectInObject:(NSObject *) rootObject forPath:(NSString *) aKeyPath {

NSArray *keys = [aKeyPath componentsSeparatedByString:@"."];
NSObject *anObject = rootObject;


for (NSString *aKey in keys) {
    int arrayIndex = 0;
    bool isArray = NO;

    // check array
    if ([[aKey substringToIndex:2] isEqualToString:@"i:"]) {
        isArray = YES;
        NSArray *values = [aKey componentsSeparatedByString:@":" ];
        arrayIndex = [[values objectAtIndex:1] intValue];
    }

    if (isArray) {
        anObject = [(NSArray *) anObject objectAtIndex:arrayIndex];
    } else {
        anObject = [(NSDictionary *) anObject objectForKey:aKey];
    }
}
return anObject;

}

Dennis Stritzke
  • 5,198
  • 1
  • 19
  • 28
0

Use SBJson as your JSON lib. Then just use this line of code (response is a string) and you will get expected output you want.

    NSMutableDictionary *responseJSON = [response JSONValue];
AAV
  • 3,785
  • 8
  • 32
  • 59