我对JSON几乎一无所知,我只需要向服务器发送请求并使用iPhone只读取来自它的数据。
我试图使用jason-framework 要做到这一点,但在阅读完文档后,我无法弄清楚如何构造对象并在请求中发送它。所以我决定改编我在SO上看到的另一个代码。
我需要的对象是:
{“code”:xxx}
我有一个问题。这个xxx是NSData,所以我怀疑我必须将这个数据转换为字符串,然后使用这个字符串来构建一个对象并在请求中发送它。
服务器响应也是一个JSON对象,格式为
{“回答”:“yyy”} 其中yyy是介于10000和99999之间的数字
这是我到目前为止的代码。
- (NSString *)checkData:(NSData) theData {
NSString *jsonObjectString = [self encode:(uint8_t *)theData length:theData.length];
NSString *completeString = [NSString stringWithFormat:@"http://www.server.com/check?myData=%@", jsonObjectString];
NSURL *urlForValidation = [NSURL URLWithString:completeString];
NSMutableURLRequest *validationRequest = [[NSMutableURLRequest alloc] initWithURL:urlForValidation];
[validationRequest setHTTPMethod:@"POST"];
NSData *responseData = [NSURLConnection sendSynchronousRequest:validationRequest returningResponse:nil error:nil];
[validationRequest release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding];
NSInteger response = [responseString integerValue];
NSLog(@"%@", responseString);
[responseString release];
return responseString;
}
- (NSString *)encode:(const uint8_t *)input length:(NSInteger)length {
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *output = (uint8_t *)data.mutableBytes;
for (NSInteger i = 0; i < length; i += 3) {
NSInteger value = 0;
for (NSInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger index = (i / 3) * 4;
output[index + 0] = table[(value >> 18) & 0x3F];
output[index + 1] = table[(value >> 12) & 0x3F];
output[index + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[index + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
ret
urn [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
}
所有这些代码都给了我错误。或者是BAD URL或java异常。
此代码有什么问题?
如果你们更喜欢使用json-framework提供另一个解决方案,请告诉我如何使用该对编码对象(“代码”,“我的NSData在这里转换为字符串”)......
感谢您的帮助。
答案 0 :(得分:17)
JSON框架支持转换数组,字典,字符串,数字和布尔值。因此,您要做的是将数据转换为这些格式之一。由于您的数据是NSData最简单的方法是将其转换为:
NSString* stringData = [[NSString alloc] initWithData:yourData
encoding:NSUTF8StringEncoding];
根据缓冲区中的内容(以及服务器是否可以处理它),您可能希望对结果进行Base64编码(如果您没有方便的话,请检查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}"; }
。将此文件发送到服务器的最简单方法是使用POST方法使用ASIHTTPRequest库。
从服务器返回结果后,JSON框架可以将其解析回字典,然后您可以获得所需的数据:
NSDictionary* responseDict = [yourJSONResponseStringFromServer JSONValue];
NSNumber* answerNum = (NSNumber *) [responseDict objectForKey:@"answer"];
int answer = [answerNum intValue];