将JSON结果转换为数组

时间:2014-02-06 06:37:16

标签: objective-c

我有这个JSON数据:

array: {
    data = (
                {
            "com_id" = 1;
            "com_name" = Apple;
        },
                {
            "com_id" = 2;
            "com_name" = "Google";
        },
               {
            "com_id" = 3;
            "com_name" = "Yahoo";
        }
    );
    message = "Data found";
    response = success;
}

这是我获取该数据的代码:

    NSURL * url = [[NSURL alloc] initWithString:@"https://jsonurlhere.com"];

    // Prepare the request object
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
                                                cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                            timeoutInterval:30];

    // Prepare the variables for the JSON response
    NSData *urlData;
    NSURLResponse *response;
    NSError *error;

    // Make synchronous request
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                    returningResponse:&response
                                                error:&error];

    // Construct a Array around the Data from the response
    NSArray* object = [NSJSONSerialization
                       JSONObjectWithData:urlData
                       options:0
                       error:&error];

    NSLog(@"array: %@", object);

现在,我想将JSON数据用于我的PickerView。如何将JSON数据更改为数组,以便我可以加载它来替换现有的数组(self.nameCompany)?

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.nameCompany = @[@"Apple", @"Google", @"Yahoo"];
}

2 个答案:

答案 0 :(得分:3)

我认为这对你很有帮助。你能试试这个链接吗?它不适用于任何支持文件。另请参阅此链接NSJSONSerialization支持的URL NSJSONSerialization

答案 1 :(得分:1)

检查此代码,您的响应不是数组而是字典。

-(void)loadData{

NSURL * url = [[NSURL alloc] initWithString:@"https://jsonurlhere.com"];

// Prepare the request object
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
                                            cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                        timeoutInterval:30];

// Prepare the variables for the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;

// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                returningResponse:&response
                                            error:&error];

// Construct a Array around the Data from the response
NSDictionary* object = [NSJSONSerialization
                   JSONObjectWithData:urlData
                   options:0
                   error:&error];

NSLog(@"array: %@", [object objectForKey:@"data"]);


NSMutableArray *companyArray=[[NSMutableArray alloc] init];

for (NSDictionary *tempDict in [object objectForKey:@"data"]) {

    [companyArray addObject:[tempDict objectForKey:@"com_name"]];
}

self.nameCompany=[NSArray arrayWithArray:companyArray];
}