两个问题。首先,您的 JSON 字符串有一个额外的逗号。它应该是:
NSString *jsonString = @"{\"firstName\":\"John\", \"lastName\": \"Smith\", \"age\": 25, \"address\": {\"streetAddress\": \"21 2nd Street\",\"city\": \"New York\", \"state\": \"NY\",\"postalCode\": \"10021\"}}";
其次,您的原始代码有误报。字符串总是会失败isValidJSONObject
。该方法不适用于验证 JSON 字符串。如果你想使用isValidJSONObject
,你应该传递一个NSDictionary
,例如:
NSDictionary* jsonDictionary = @{
@"firstName" : @"John",
@"lastName" : @"Smith",
@"age" : @(25),
@"address" : @{
@"streetAddress": @"21 2nd Street",
@"city" : @"New York",
@"state" : @"NY",
@"postalCode" : @"10021"
}
};
BOOL valid = [NSJSONSerialization isValidJSONObject:jsonDictionary];
if (valid) {
NSLog(@"Valid JSON");
} else {
NSLog(@"Invalid JSON");
}
因此,创建 JSON 字符串的最佳方法是像上面一样创建字典,然后调用dataWithJSONObject
. 我通常建议不要手动编写 JSON 字符串,因为您总是可以引入诸如额外逗号之类的拼写错误。我总是从这样的一个 JSON 字符串中构建一个 JSON 字符串NSDictionary
,因为您永远不必担心字符串是否格式正确。NSJSONSerialization
负责正确格式化字符串的艰苦工作:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary
options:0
error:&error];
if (error)
NSLog(@"dataWithJSONObject error: %@", error);
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSLog(@"JSON string is: %@", jsonString);
这会产生:
{"age":25,"lastName":"Smith","firstName":"John","address":{"streetAddress":"21 2nd Street","state":"NY","city":"New York","postalCode":"10021"}}
或者,如果您使用以下NSJSONWritingPrettyPrinted
选项dataWithJSONObject
:
{
"age" : 25,
"lastName" : "Smith",
"firstName" : "John",
"address" : {
"streetAddress" : "21 2nd Street",
"state" : "NY",
"city" : "New York",
"postalCode" : "10021"
}
}