繁体   English   中英

JSON IPHONE:如何发送JSON请求并从服务器提取数据?

[英]JSON IPHONE: How to send a JSON request and pull the data from a server?

我对JSON几乎一无所知,我需要向服务器发送请求,并仅使用iPhone来读取来自它的数据。

我曾尝试使用jason-framework来做到这一点,但在阅读完文档后,我无法弄清楚如何构造对象并在请求中发送它。 所以我决定修改我在这里看到的另一个代码。

我需要的对象是这样的:

{“code”:xxx}

我有一个问题。 这个xxx是NSData,所以我怀疑我必须将这个数据转换为字符串,然后使用这个字符串来构建一个对象并在请求中发送它。

服务器响应也是表单中的JSON对象

{“answer”:“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在这里转换为字符串”)...

谢谢你的帮助。

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}"; } "code" : "{yourstringdata}"; } 将此文件发送到服务器的最简单方法是使用带有POST方法的ASIHTTPRequest库。

一旦从服务器返回结果,JSON框架就可以将其解析回字典,然后您可以获得所需的数据:

NSDictionary* responseDict = [yourJSONResponseStringFromServer JSONValue];
NSNumber* answerNum = (NSNumber *) [responseDict objectForKey:@"answer"];
int answer = [answerNum intValue];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM