【问题标题】:Nested Dictionary in JSONModelJSONModel 中的嵌套字典
【发布时间】:2014-03-07 19:54:49
【问题描述】:

创建 JSONModel 时出现错误。

Error Domain=JSONModelErrorDomain Code=1 “无效的 JSON 数据:尝试使用 initWithDictionary 初始化 JSONModel 对象:错误:但字典参数不是 'NSDictionary'。” UserInfo=0x9bc2340 {kJSONModelKeyPath=categories.Data, NSLocalizedDescription=无效的 JSON 数据:尝试使用 initWithDictionary 初始化 JSONModel 对象:错误:但字典参数不是“NSDictionary”。}

这是我收到的回复...

{
    "categories": {
        "Data": [
            {
                "Id": 19,
                "Name": "",
                "Description": "",
                "ImageURL": "",
                "FullSizeImageUrl": "",
                "ParentCategoryId": 0
            }
        ],
        "Total": 1
    }
}

这是我的模型

@interface CategoryResponse : JSONModel
@property (strong, nonatomic) NSDictionary <Categories> *categories;
@end

@protocol Categories @end
@interface Categories : JSONModel
@property (assign, nonatomic) int Total;
@property (strong, nonatomic) NSArray<CategoryData> *Data;
@end

@protocol CategoryData @end
@interface CategoryData : JSONModel
@property (strong, nonatomic) NSString <Optional> *Name;
@property (strong, nonatomic) NSString <Optional> *Description;
@property (strong, nonatomic) NSString <Optional> *ImageURL;
@property (strong, nonatomic) NSString <Optional> *FullSizeImageUrl;
@property (assign, nonatomic) int Id;
@property (assign, nonatomic) int ParentCategoryId;

void (^success)(AFHTTPRequestOperation *, id) = ^(AFHTTPRequestOperation *op, id data) {
    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSError *error;

    categories = [[CategoryResponse alloc] initWithString:responseString error:&error];

    complete(nil, categories);
};

我意识到@property (strong, nonatomic) NSDictionary &lt;Categories&gt; *categories; 不是这样做的正确方法,但我不知道是什么。

【问题讨论】:

  • "但字典参数不是 'NSDictionary'。"这对你说了什么???
  • 异常堆栈跟踪在哪里?
  • 我认为您的 CategoryResponse 对象应该编码为@property (strong, nonatomic) Categories *categories;
  • 你能处理响应数据来生成你的字典吗:[NSJSONSerialization jsonObjectWithData:data..]
  • HotLicks - 这就是解决方案。当我挂断电话时,我想我盯着屏幕太久了:)如果你想发布答案,我会接受。

标签: ios objective-c json nsdictionary jsonmodel


【解决方案1】:

我想您可以这样处理字典的分配:

void (^success)(AFHTTPRequestOperation *, id) = ^(AFHTTPRequestOperation *op, id 数据) {
    类别 = [NSJSONSerialization JSONObjectWithData:数据选项:0 错误:无];

    完成(无,类别);
};

虽然我对 AFNetworking 不是很熟悉,因为我喜欢使用 NSURLConnection。

【讨论】:

  • initWithString 处理 JSON 解码。
  • 没错,但是为什么数据-> 字符串-> 字典当你可以数据-> 字典的时候呢?感谢您的反对票,很高兴您对自己感觉良好
  • 因为 OP 使用的是 JSONModel 工具包,这就是它定义事物的方式。这是一个 Jackson 崇拜工具包,可以从 JSON 创建完整的 Objective-C 对象,而不是暴露字典和数组。 (换句话说,你的回答是“没用”。)
  • 关键是要获取 JSON 来创建模型,不是吗?最有可能使用 NSURLConnection 和 NSJSONSerialization 的库。我个人觉得你的逻辑令人反感且无用。
  • 重点是从 JSON 中创建一个 CategoryResponse 对象。
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 2018-05-31
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 2012-01-29
相关资源
最近更新 更多