ios - JSON 字符串不会被解析

标签 ios json parsing ios5

我正在尝试从网络服务中解析一个 JSON 字符串。传入的字符串如下所示:

{
"Faculty_Members": [
    {
        "ID": 3377,
        "First_Name": "John",
        "Last_Name": "Doe"
    }
]
}

我的 IOS 代码如下所示:

NSURL *jsonUrl = [NSURL URLWithString:@"http://website/Service1.svc/Names"];
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:jsonUrl options:kNilOptions error:&error];
NSMutableDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
NSLog(@"%@",jsonResponse);

//parse out the json data
if([NSJSONSerialization isValidJSONObject:jsonResponse])
{
NSLog(@"YEP");
  }else{
NSLog(@"NOPE");
}

日志将显示正确的 JSON 数据,但我一直在 isValidJsonObject 上收到“NOPE”。

Web 服务正在将数据作为数据类型“字符串”发回。这有什么区别吗?如果是这样,我应该将其发回什么数据类型?

任何想法将不胜感激!

最佳答案

您不使用 isValidJSONObject: 来测试有效的 JSON 字符串,您使用它来测试可以转换为 JSON 的对象;参见 the documentation :

isValidJSONObject:

Returns a Boolean value that indicates whether a given object can be converted to JSON data.

+ (BOOL)isValidJSONObject:(id)obj

Parameters:

obj
The object to test.


Return Value:

YES if obj can be converted to JSON data, otherwise NO.

相反,只需使用 JSONObjectWithData: 照常解析数据;如果失败,它将在 error 中返回一个 NSError

关于ios - JSON 字符串不会被解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9484194/

相关文章:

java - 解析 JSONArray 时出现的 Jersey 问题

java - 正在解析HH :mm (with two digits minute) to LocalTime with JodaTime

ios - 如何在 View Controller 之间同步索引

ios - 用于移动应用程序的 Restful Web 服务 - 什么语言、框架、基础设施?

ios - NSCalendar 一个月内的最大天数

java - 如何解压缩 jsonlz4 Mozilla Firefox session 文件?

javascript - 循环遍历 json 对象并提取数据 - js

jquery - Phonegap 跨平台应用获取外部数据

java - 如何解析服务器的 JSON 响应并进行比较

c# - DraggableView C# Xamarin 的恢复位置命令