-1

您好我正在尝试将本地数据转换为 iOS 上的 json 格式。格式如下,

{
    "answers": [
        {
            "question_id": 2,
            "answer": "4",
            "question_instance_id": 146
        },
        {
            "question_id": 2,
            "answer": "4",
            "question_instance_id": 147
        },
        {
            "question_id": 2,
            "answer": "4",
            "question_instance_id": 148
        },
        {
            "question_id": 3,
            "answer": "Hdhd",
            "question_instance_id": 149
        }
    ],
    "last_name": "Jd",
    "first_name": "Js",
    "survey_id": 41
}

我浏览了各种博客,他们解释了 json 编码。但是我仍然无法弄清楚如何处理嵌套字典以将数据转换为 json 格式,如本示例中给出的那样。

我很感激任何帮助。

4

3 回答 3

1

您需要为此使用NSJSONSerialization,您需要的内容将自动完成。另请查看链接。谢谢


这是链接的 Wonderlich 教程的 30 秒摘要,它可能对某人有所帮助。干杯。

你需要知道的关于 json 的一切,它甚至不会在 SO 上滚动 :)

#define exampleURL [NSURL URLWithString:\
 @"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]
-(void)viewDidLoad { [super viewDidLoad]; [self _jsonGet]; }

-(void)_jsonGet
    {
    NSLog(@"I'm getting some JSON data from the net.");
    dispatch_async(dispatch_get_main_queue(),
        ^{
        NSData* dataFromNet = [NSData dataWithContentsOfURL:exampleURL];
        [self _jsonParse:dataFromNet];
        });
    }

-(void)_jsonParse:(NSData *)jdat
    {
    NSLog(@"I did seem to get the data .. now parsing" );
    NSError* error;
    NSDictionary* jdic = [NSJSONSerialization JSONObjectWithData:jdat
        options:kNilOptions
        error:&error];
    // do this NSLog(@"%@", jdic); to see the fields available

    NSArray* latestLoans = [jdic objectForKey:@"loans"];
    NSLog(@"loans.count: %d \n\n\n", latestLoans.count);
    NSDictionary *oneLoan = latestLoans[3];
    NSLog(@"loans[3]: %@ \n\n\n\n", oneLoan);

    NSLog(@"...name: %@ \n\n\n\n", [oneLoan objectForKey:@"name"] ); 
    NSLog(@"...sector: %@ \n\n\n\n", [oneLoan objectForKey:@"sector"] ); 
    }
于 2013-10-24T15:07:26.077 回答
0

简单地:

  NSDictionary *entireJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

您内部的逻辑NSDictionary与您的 JSON 相同。对于您的答案,您可以这样:

NSArray *answersArray = entireJSon[@"answers"];

快速注意,确保您的 json 有效(在这种情况下是......)

于 2013-10-24T15:05:20.113 回答
0

如果您熟悉 iOS 数组和字典,那么您可以想象它们与 JSON 的关系。JSON 只是数组和字典的编码,因此如果您将数据匹配到与您所拥有的相关的结构中,JSON 编码将是相同的。

如果您将上述 JSON 粘贴到这样的 JSON 解析器中:

JSON解析器页面

可以看到底层结构:

具有 4 个键/值对的字典,键:“Answers”、“last_name”、“first_name”和“survey_id”。键的所有值都是原语、字符串或数字,除了第一个“answers”,它的值是一个子字典数组,都带有键:“question_id”、“answer”和“question_instance_id”

于 2013-10-24T15:15:34.597 回答