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

前端 未结 1 738
迷失自我
迷失自我 2021-01-31 23:48

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.

I have tried to use the jason-framewor

相关标签:
1条回答
  • 2021-02-01 00:40

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

    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.

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

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

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

    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.

    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];
    
    0 讨论(0)
提交回复
热议问题