JSON IPHONE:如何发送JSON请求并从服务器中提取数据? [英] JSON IPHONE: How to send a JSON request and pull the data from a server?

查看:93
本文介绍了JSON IPHONE:如何发送JSON请求并从服务器中提取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

我需要的对象是:

{code:xxx}

{ "code" : xxx }

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

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.

服务器响应也是一个JSON对象,格式为

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

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

{ "answer" : "yyy" } where yyy is a number between 10000 and 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];
}

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

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

此代码有什么问题?

如果你们愿意给予使用json框架的另一个解决方案请告诉我如何使用该对编码对象(代码,我的NSData在这里转换为字符串)...

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

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:

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

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

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.

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

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

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

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

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

NSString* jsonString = [jsonDictionary JSONRepresentation];

将其转储出去,你会看到你的JSON字符串 - 例如:{code:{yourstringdata}; } 。将此信息发送到服务器的最简单方法是使用POST方法使用 ASIHTTPRequest 库。

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框架就可以将其解析回字典,然后你可以得到你需要的数据:

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:

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

这篇关于JSON IPHONE:如何发送JSON请求并从服务器中提取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆