如何从Worklight中调用的适配器解析JSON字符串



我们在服务器中有一个JSON文件。我们能够检索JSON文件,但显然无法获取嵌套JSON中的项。

以下是我们的代码片段:

- (void)onSuccess:(WLResponse *)response{
    NSLog(@"Connection Success: %@",response);
    NSString *resultText;
    if ([response responseText] != nil) {
        resultText = [response responseText];
        NSDictionary *allData = [response getResponseJson];
        NSDictionary *resultData = allData[@"result"];
        ...
      }
}

以下是我们的JSON文件结构:

{"contacts":[
    {
        "name":"name 1",
        "address":"address 1"
    },
    {
        "name":"name 2",
        "address":"address 2"
    },
    {
        "name":"name 3",
        "address":"address 3"
    }
]}

您可以在客户端上拥有NSDictionary后使用valueForKeyPath:。

例如,伪代码:

NSArray* contacts = [allData valueForKeyPath:@"result.contacts"];
NSString* firstContactName = contacts[0][@"name"];

我假设allData引用的NSDictionary在results.contacts密钥路径中具有联系人NSArray。如果不是这样,请根据NSDictionary的结构进行修改。

最新更新