0

我最近一直在研究 iOS 平台的网络方面。我想将 JSON 提要合并到我的应用程序中。所以我有几个问题:

  1. 解析 JSON 对象并检索它们的最佳内置类是什么?
  2. JSON数据下载后,如何存储和使用?

我使用NSURLandNSURLRequest吗?

我是iOS开发新手,请帮助我。谢谢你。

4

5 回答 5

3

一般来说,您可能应该使用 NSJSONSerialization,因为这是 Apple 的内置功能。但至少还有六个其他选项——请参阅 json.org 获取列表。

您可以选择将 JSON 保存为字符串并将其作为字符串存储在文件中,或者将其解析为 Objective-C 对象(NSArray 和 NSDictionary),或者对其进行解析,然后将其中的数据存储在数据库中。通常,对于不太大的 JSON 结构的短期使用,第二种选择是可行的方法。

在 json.org 上学习并理解 JSON 语法——它非常简单,需要 5-10 分钟的时间来学习,而且你可以为自己省去很多麻烦。并且了解 NSLog 以非常类似于 JSON 的格式转储 NSArray 和 NSDictionary 对象,但使用()for 数组而不是[],并且=for 键/值对而不是:.

PS:请不要随便找个例子,一味的照搬。每个 JSON 源都不同,您必须了解其结构才能知道如何将其分开。 了解你在做什么,事情会进展得更快。

于 2013-09-10T15:11:12.933 回答
2

I suggest you to use the AFNetworking framework you can donwload it here

Here is the documentation about the JSON requests :
http://cocoadocs.org/docsets/AFNetworking/1.3.2/Classes/AFJSONRequestOperation.html

You can also have a look here for an example of how to use it.

于 2013-09-10T15:00:47.987 回答
0

The best way to retrieve the JSON data depends on your use case, therefore, I can not help you with that.

Parsing JSON is very straight forward in iOS. You just convert the JSON Data to a NSArray or NSDictionary (depending on the root element of your JSON data) with the NSJSONSerialization class.

Example downloading and parsing JSON (with an array as base object) from a web service:

The JSON is supposed to have a format similar to ["1","2","last"] in this example.

in the .h:

@interface WSHandler : NSObject <NSURLConnectionDelegate>
{
    NSMutableData *receivedData;
}

- (void)callWebService;
@end

in the .m:

#import "WSHandler.h"

@implementation WSHandler
- (void)callWebService
{   

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:/* here goes your WS URL*/]];

    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (connection)
    {
        receivedData = nil;
    }
    else
    {
        NSLog(@"Connection could not be established");
    }
}

#pragma mark - NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (!receivedData)
        receivedData = [[NSMutableData alloc] initWithData:data];
    else
        [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"***** Connection failed");

    receivedData=nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    NSLog(@"***** Succeeded! Received %d bytes of data",[receivedData length]);
    NSLog(@"***** AS UTF8:%@",[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]);

    //JSON parsing
    NSError *err = nil;
    NSArray *receivedDataArray = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:&err];

    if (receivedDataArray==nil || receivedDataArray.count<=0 || err)
    {
        DLog(@"***** Error! %@", [err localizedDescription]);
    }
    else
    {
        //logs each element of the array
        for (int i=0;i<receivedDataArray.count;i++)
        {
            NSLog(@"Element %i = %@",i,[receivedDataArray objectAtIndex:i]);
        }       
    }    
}
@end
于 2013-09-10T14:59:39.320 回答
0

序列化 json 的内置方法是NSSerilization

用作:

NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //  json data

反序列化为:

NSArray *arrayOfJson = [NSJSONSerialization JSONObjectWithData:response
options:0 error:&jsonParsingError];

但是应该知道json返回的是什么格式。那可以是 NSArray 或 NSDictionary。

从 JSON 获取数据

for(int i=0; i<[arrayOfJson count];i++)
{
    arr= [arrayOfJson objectAtIndex:i];
    NSLog(@”Json value: %@”, [arr objectForKey:@"youJSONKey"]);
}
于 2013-09-10T14:58:11.203 回答
0

对于我的应用程序中的 JSON 帖子,我使用 SBJson。此方法使用 NSURLConnection 和 HTTP Post 请求。解析后的返回数据将以 NSDictionary 中的键和字符串的形式出现。(jsonData 是在其他地方建立的 NSDictionary)(显然 NSJSONSerialization 做同样的事情)

(void) doJson:(NSString *)post {

CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, FALSE);

NSURL *url=[NSURL URLWithString:@"youraddress"];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

// [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

SBJsonParser *jsonParser = [SBJsonParser new];
jsonData = [jsonParser objectWithString:responseData error:nil];

NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
于 2013-09-10T14:48:17.677 回答