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

时间:2022-02-14 01:45:22

I know barely nothing about JSON and I need to send a request to a server and read the data coming from it, using the iPhone only.

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

I have tried to use the jason-framework to do that, but after readin the documentations I was not able to figure out how to construct the object and send it on the request. So I decided to adapted another code I saw here on SO.

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

The Object I need is this:

我需要的对象是这样的:

{ "code" : xxx }

{“code”:xxx}

Here I have a problem. This xxx is a NSData, so I suspect that I have to convert this data to a string, then use this string to build an object and send this on the request.

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

the server response is also a JSON object, in the form

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

{ "answer" : "yyy" } where yyy is a number between 10000 and 99999

{“answer”:“yyy”}其中yyy是介于10000和99999之间的数字

this is the code I have so far.

这是我到目前为止的代码。

- (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];
}

all this code gives me is errors. Or BAD URL or java exception.

所有这些代码都给了我错误。或者是BAD URL或java异常。

What is wrong with this code?

这段代码有什么问题?

If you guys prefer to give another solution using the json-framework please tell me how to encode the object using that pair ("code", "my NSData here converted to string")...

如果你们更喜欢使用json-framework提供另一个解决方案,请告诉我如何使用该对编码对象(“代码”,“我的NSData在这里转换为字符串”)...

thanks for any help.

谢谢你的帮助。

1 个解决方案

#1


17  

JSON framework supports converting Arrays, Dictionaries, Strings, Numbers, and Booleans. So what you want to do is convert your data to one of these formats. Since your data is NSData easiest way is to convert it with:

JSON框架支持转换数组,字典,字符串,数字和布尔值。因此,您要做的是将数据转换为这些格式之一。由于您的数据是NSData最简单的方法是将其转换为:

NSString* stringData = [[NSString alloc] initWithData:yourData
                                             encoding:NSUTF8StringEncoding];

Depending on what's in the buffer (and if your server can handle it) you may want to Base64 encode the result (check http://www.cocoadev.com/index.pl?BaseSixtyFour if you don't have a converter handy). You could even go straight from NSData to a Base64-encoded string.

根据缓冲区中的内容(以及服务器是否可以处理它),您可能需要对结果进行Base64编码(如果您没有方便的话,请查看http://www.cocoadev.com/index.pl?BaseSixtyFour) 。您甚至可以直接从NSData转换为Base64编码的字符串。

Now create a dictionary with one item with key code and value stringData (from last step):

现在创建一个字典,其中包含一个带有键代码和值stringData的项(从上一步开始):

NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObject:stringData
                                                           forKey:@"code"];

This can be easily converted to JSON. Just import JSON.h in your code header, then use:

这可以很容易地转换为JSON。只需在代码头中导入JSON.h,然后使用:

NSString* jsonString = [jsonDictionary JSONRepresentation];

Dump it out and you'll see your JSON string -- something like: { "code" : "{yourstringdata}"; }. Easiest way to send this over to your server is to use the ASIHTTPRequest library with a POST method.

将它转储出来,你会看到你的JSON字符串 - 类似于:{“code”:“{yourstringdata}”; }。将此文件发送到服务器的最简单方法是使用带有POST方法的ASIHTTPRequest库。

Once you get the result back from the server the JSON framework can parse it back into a dictionary and then you can get out the data you need:

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

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

#1


17  

JSON framework supports converting Arrays, Dictionaries, Strings, Numbers, and Booleans. So what you want to do is convert your data to one of these formats. Since your data is NSData easiest way is to convert it with:

JSON框架支持转换数组,字典,字符串,数字和布尔值。因此,您要做的是将数据转换为这些格式之一。由于您的数据是NSData最简单的方法是将其转换为:

NSString* stringData = [[NSString alloc] initWithData:yourData
                                             encoding:NSUTF8StringEncoding];

Depending on what's in the buffer (and if your server can handle it) you may want to Base64 encode the result (check http://www.cocoadev.com/index.pl?BaseSixtyFour if you don't have a converter handy). You could even go straight from NSData to a Base64-encoded string.

根据缓冲区中的内容(以及服务器是否可以处理它),您可能需要对结果进行Base64编码(如果您没有方便的话,请查看http://www.cocoadev.com/index.pl?BaseSixtyFour) 。您甚至可以直接从NSData转换为Base64编码的字符串。

Now create a dictionary with one item with key code and value stringData (from last step):

现在创建一个字典,其中包含一个带有键代码和值stringData的项(从上一步开始):

NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObject:stringData
                                                           forKey:@"code"];

This can be easily converted to JSON. Just import JSON.h in your code header, then use:

这可以很容易地转换为JSON。只需在代码头中导入JSON.h,然后使用:

NSString* jsonString = [jsonDictionary JSONRepresentation];

Dump it out and you'll see your JSON string -- something like: { "code" : "{yourstringdata}"; }. Easiest way to send this over to your server is to use the ASIHTTPRequest library with a POST method.

将它转储出来,你会看到你的JSON字符串 - 类似于:{“code”:“{yourstringdata}”; }。将此文件发送到服务器的最简单方法是使用带有POST方法的ASIHTTPRequest库。

Once you get the result back from the server the JSON framework can parse it back into a dictionary and then you can get out the data you need:

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

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