小编ino*_*not的帖子

如何使用JSON-Framework在XCode上检测JSON对象/ JSON数组

我在JSON解析方面遇到了一些问题.当我点击URL时,我得到了像这样的JSON响应:

//JSON 1
{ "data":
  {"array":
    ["3",
       {"array":
          [
            {"id":"1","message":"Hello","sender":"inot"},
            {"id":"2","message":"World","sender":"inot"},
            {"id":"3","message":"Hi","sender":"marza"}
          ]
        }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}
Run Code Online (Sandbox Code Playgroud)

但是如果数据的结果只是1,那么JSON响应是这样的:

//JSON 2
{ "data":
  {"array":
    ["3",
       {"array":
          {"id":"3","message":"Hi","sender":"marza"}
       }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}
Run Code Online (Sandbox Code Playgroud)

我实现此代码以获取id,message和sender值,并在JSON 1上正常工作,但在JSON 2上出错.我使用JSON-Framework.问题是如何检测JSON响应是对象({})还是数组([])?

// 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(@"id      = %@",[item objectForKey:@"id"]); …
Run Code Online (Sandbox Code Playgroud)

iphone json json-framework

5
推荐指数
1
解决办法
6883
查看次数

标签 统计

iphone ×1

json ×1

json-framework ×1