【问题标题】:IOS JSON - Getting unexpected results in the consoleIOS JSON - 在控制台中获得意外结果
【发布时间】:2016-07-25 21:50:22
【问题描述】:

我是 JSON 新手,并试图像这样遍历我的 JSON 数组

for (NSDictionary *dict in self.contentArray) {
        NSLog(@"%@", dict);
}

但是在控制台中继续获取这种类型的内容而不是实际的字典:

<Content: 0x7fd9b1037950>

这是我用来创建数组的代码:

    // Create a new array to hold the locations
    NSMutableArray *locations = [[NSMutableArray alloc] init];

    // Get an array of dictionaries with the key "locations"
    NSArray *array = [jsonDictionary objectForKey:@"data"];
    // Iterate through the array of dictionaries
    for(NSDictionary *dict in array) {
        // Create a new Location object for each one and initialise it with information in the dictionary
        Content *content = [[Content alloc] initWithJSONDictionary:dict];
        // Add the Location object to the array
        [locations addObject: content];
   }

【问题讨论】:

  • 因为这就是您的阵列中的实际内容。你是如何创建数组的?
  • 将代码编辑到您的问题中,使其真正可读。
  • 你得到了预期的行为,你还期待什么?您正在存储一个内容对象并获得它。
  • 以为我会收到这样的东西:
  • @ldindu { "section" : "0", "ch1" : "", "ch2" : "", "description": "" },

标签: ios objective-c json nsmutablearray nsmutabledictionary


【解决方案1】:

你可以做两件事来实现你想要的行为。

  1. 在您的 Content 类中重写以下方法

    (NSString *)description;
    

    当使用 NSLog 打印 Content 实例时,根据需要格式化并返回字符串。

  2. 将 dict 直接存储在数组中,而不将其包裹在 Content 对象周围,然后字典将按照您的预期打印。

【讨论】:

  • 我认为 OP 想要 JSON 输出,所以有比这更好的选择。
【解决方案2】:

您可以使用 JSONModel:https://github.com/jsonmodel/jsonmodel

很简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多