如何在Objective c中更改JSON输出格式

时间:2017-01-24 12:13:55

标签: ios objective-c arrays json nsmutablearray

您好我是iOS开发新手,请帮我解决这个问题

我能够以下面的格式检索JSON值:还附加了我用来检索json输出的代码

我的代码:

 NSData *cityData = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];


NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:strURL]];

        __block NSDictionary *json;
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                   json = [NSJSONSerialization JSONObjectWithData:data
                                                                          options:0
                                                                            error:nil];
                                   NSLog(@"Async JSON: %@", json);
                               }];

这就是我得到输出的方式:

Async JSON: (
        {
        "job_code" = SRTCN01121;
        "job_id" = 1121;
    },
        {
        "job_code" = SRTCN01126;
        "job_id" = 1126;
    }
)

但这不是我需要的,我需要json输出格式如下:

Async JSON: (
            (
            SRTCN01121,
             1121
        ),
            (
            SRTCN01126,
            1126
        )
    )

请帮我解决这个问题

1 个答案:

答案 0 :(得分:0)

您可以拥有一个模型类,您可以在其中存储每组数据的值

@interface Job : NSObject
@property(nonatomic, assign) NSInteger jobID;
@property(nonatomic, copy) NSString *jobCode;
@end

现在这里是一段可用于解析JSON数据的代码。考虑到你有NSDictionary json有JSON响应

  

注意 :()在JSON响应中表示数组,而{}表示字典。

     

您的回复中嵌套了词典。

- (NSArray *)parseResponse:(NSDictionary *)jsonResponse
{
    NSMutableArray *responseArray = [NSMutableArray array];

   for (NSDictionary *dictionary in jsonResponse) 
   {
        Job *job = [[Job alloc] init];
        job.jobID = [[dictionary valueForKey:@"job_id"] integerValue];
        job.jobCode = [dictionary valueForKey:@"job_code"]; 

        [responseArray addObject:job];
    }

    return [responseArray copy];
}                                                          

以下是您可以从阵列访问数据的方式。

- (void)printResponse:(NSArray *)array
{
    for(Job *job in array)
    {
        NSLog(@"Code : %@, ID : %ld", job.jobCode, job.jobID);
    }
}

希望这有帮助。