簡體   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