iOS解析特定jSON
我遇到了解析jSON的问题,我有这样一个jSON:iOS解析特定jSON,ios,json,parsing,Ios,Json,Parsing,我遇到了解析jSON的问题,我有这样一个jSON: { "id": 0, "message": "ok" } 我尝试了几种方法来获取“id”和“message”的值,但我总是出错 我怎样才能选择“id”和“message”的值 (我在NSMutableArray中获得我的JSON的结果) 编辑: NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; NSData *re
{
"id": 0,
"message": "ok"
}
我尝试了几种方法来获取“id”和“message”的值,但我总是出错
我怎样才能选择“id”和“message”的值
(我在NSMutableArray
中获得我的JSON
的结果)
编辑:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSMutableDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:publicTimeline.allKeys];
[sortedArray sortUsingSelector:@selector(localizedStandardCompare:)];
return sortedArray;
试试这个
将JSON响应解析为NSDictionary
NSDictionary * responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *message = [responseDictionary valueForKey:@"message"];
JSON字符串表示字典。因此,您必须使用
NSDictionary
而不是NSArray
编辑I
// convert dictionary into JSON
NSDictionary *fromDict = @{@"id": @(0), @"message": @"ok"};
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:fromDict options:0 error:nil];
// convert data (like you get from an API request) to dictionary
NSDictionary *toDict = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
我认为这对您很有帮助(在这个响应中,您将获得第一个字典,字典包含两个键。so)
我认为这对你很有用 您提供的JSON格式为
NSDictionary
。将JSON解析为NSDictionary
并使用[responseDictionary valueForKey:@“message”]
你能显示你的代码吗?我正在使用它来执行Web服务并获取JSON:I编辑了我的帖子。上面的JSON示例是完整响应还是部分响应?对于这种情况,完整响应是我试图将NSMutableArray转换为NSData,但是,日志显示id和message为“null”:/@developest您不需要将任何内容转换为NSData,代码中的数组只提供字典中的键。正如所有答案所示,您可以直接从JSON返回的字典中获取这两个值parser@deveLost-你迷路了--这是毫无疑问的。@developst:你的编辑现在可以和我的更正一起使用了吗?它不是一个NSMutableDictionary。NSJSONSerialization(没有选项)返回的是一个NSDictionary,不是一本易变的字典。不能将NSDictionary当作NSMutableDictionary来使用。
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSString *message = [publicTimeline valueForKey:@"message"];