如何使用JSON-Framework在iPhone SDK(XCode)中解析JSON对象

ino*_*not 8 iphone xcode parsing json

我有这样的JSON对象:

{ "data":
  {"array":
    ["2",
       {"array":
          [
            {"clientId":"1","clientName":"Andy","job":"developer"},
            {"clientId":"2","clientName":"Peter","job":"carpenter"}
          ]
        }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}
Run Code Online (Sandbox Code Playgroud)

我想使用JSON-Framework获取array [0] value(2)和array [1]值(clientId,clientName,job).你知道怎么做吗?

dea*_*rne 21

假设您已按照说明将 JSON-Framework 安装到项目中,以下是您使用它的方法(取自此处的文档):

// 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"]);
Run Code Online (Sandbox Code Playgroud)


ino*_*not 6

谢谢你的回答,我的问题解决了,我从你的代码中修改了一下,这里有:

// 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"]);
}
Run Code Online (Sandbox Code Playgroud)