views:

477

answers:

4

Hello All, I have JSON object like this :

{ "data":
  {"array":
    ["2",
       {"array":
          [
            {"clientId":"1","clientName":"Andy","job":"developer"},
            {"clientId":"2","clientName":"Peter","job":"carpenter"}
          ]
        }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}

I want to get the array[0] value (2) and array[1] value (clientId, clientName, job) using JSON-Framework. Do you have any idea how to do that?

+1  A: 

Hi,

Assuming you've followed the instructions to install JSON-Framework into your project, here's how you use it (taken from the docs here) :

// Parse the string into JSON
NSDictionary *json = [myString JSONValue];

// Get the objects you want, e.g. output the second item's client id
NSArray *items = [json valueForKeyPath:@"data.array"];
NSLog(@" client Id : %@", [[items objectAtIndex:1] objectForKey:@"clientId"]);
deanWombourne
A: 

Hi Dean, thank you for your answer, my problem solved, I modify a little bit from your code, here are:

// Parse the string into JSON
NSDictionary *json = [myString JSONValue];

// Get all object
NSArray *items = [json valueForKeyPath:@"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
   NSLog(@"clientId = %@",  [item objectForKey:@"clientId"]);
   NSLog(@"clientName = %@",[item objectForKey:@"clientName"]);
   NSLog(@"job = %@",       [item objectForKey:@"job"]);
}
inot
A: 

how to store this data in NSMUtableArray ??

while (item = (NSDictionary*)[enumerator nextObject]) {
   NSLog(@"clientId = %@",  [item objectForKey:@"clientId"]);//this 
   NSLog(@"clientName = %@",[item objectForKey:@"clientName"]);//this
   NSLog(@"job = %@",       [item objectForKey:@"job"]);//this
}
prajakta
A: 

We need 1 class, let say MyData.h and MyData.m

//MyData.h
@interface MyData : NSObject {
    NSString *clientId;
    NSString *clientName;
    NSString *job;
}

@property (nonatomic, retain) NSString *clientId;
@property (nonatomic, retain) NSString *clientName;
@property (nonatomic, retain) NSString *job;

@end

//MyData.m
@implementation MyData

@synthesize clientId, clientName, job;

- (void)dealloc{    
    [clientId release];
    [clientName release];
    [job release];
    [super dealloc];
}

@end
//-------------------------------------

To store our data :

NSMutableArray *dataArray = [[NSMutableArray alloc]init];
while (item = (NSDictionary*)[enumerator nextObject]) {
    MyData *aMyData = [[MyData alloc] init];
    aMyData.clientId   = [item objectForKey:@"clientId"];
    aMyData.clientName = [item objectForKey:@"clientName"];
    aMyData.job        = [item objectForKey:@"job"];
    [dataArray addObject:aMyData];
    [aMyData release];
    aMyData = nil;
}
inot