JSON 框架支持转换数组、字典、字符串、数字和布尔值。因此,您要做的就是将数据转换为这些格式之一。由于您的数据是 NSData,最简单的方法是将其转换为:
NSString* stringData = [[NSString alloc] initWithData:yourData
encoding:NSUTF8StringEncoding];
根据缓冲区中的内容(以及您的服务器是否可以处理它),您可能需要对结果进行 Base64 编码(检查http://www.cocoadev.com/index.pl?BaseSixtyFour http://www.cocoadev.com/index.pl?BaseSixtyFour如果你手边没有转换器)。您甚至可以直接从 NSData 转换为 Base64 编码的字符串。
现在创建一个字典,其中包含一个带有键的项目code
和价值stringData
(从上一步开始):
NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObject:stringData
forKey:@"code"];
这可以轻松转换为 JSON。只需在代码头中导入 JSON.h,然后使用:
NSString* jsonString = [jsonDictionary JSONRepresentation];
将其转储出来,您将看到 JSON 字符串——类似于:{"code" : "{yourstringdata}"; }
。将其发送到服务器的最简单方法是使用ASIHTTP请求 http://allseeing-i.com/ASIHTTPRequest/具有 POST 方法的库。
一旦你从服务器返回结果,JSON 框架就可以将其解析回字典中,然后你就可以获取你需要的数据:
NSDictionary* responseDict = [yourJSONResponseStringFromServer JSONValue];
NSNumber* answerNum = (NSNumber *) [responseDict objectForKey:@"answer"];
int answer = [answerNum intValue];