【问题标题】:How to change the JSON output format in Objective c如何在 Objective c 中更改 JSON 输出格式
【发布时间】:2017-06-09 05:46:07
【问题描述】:

您好,我是 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
        )
    )

请帮我解决这个问题

【问题讨论】:

  • 一切都很好,你可以直接使用键访问值,无需检索,这是我的建议
  • @Tela:所以你只是想要这些值,对吧?

标签: ios objective-c arrays json nsmutablearray


【解决方案1】:

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

@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);
    }
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多