美文网首页iOS技术iOS网络篇
iOS中JSONModel的使用

iOS中JSONModel的使用

作者: jueyingxx | 来源:发表于2015-03-31 16:03 被阅读40644次

流弊的JSON数据模型框架

https://github.com/jsonmodel/jsonmodel

版本 1.3.0


如果你喜欢JSONModel,并且使用了它,请你:

  • star一下

  • 给我一些反馈. 多谢!


JSONModel for iOS and OSX

JSONModel 是一个能够快速巧妙的创建数据模型的库. 你可以在 iOS or OSX APP中使用它.

JSONModel 自动检查JOSN模型和结构体, 彻底的减少你的代码量.


添加JSONModel到你的项目中

要求

  • 支持持ARC; iOS 5.0+ / OSX 10.7+
  • SystemConfiguration.framework

as: 1) 源文件

1.下载JSONModel.zip文件
2.将它拷贝到你的项目中
3.导入SystemConfiguration.framework框架

or 2)使用 CocoaPods

pod 'JSONModel'

如果你想关于CocoaPods了解更多,请参考这个简单的教程.

or 3) 使用 Carthage

在你的项目的Cartfile添加JSONModel:

github "jsonmodel/jsonmodel"

文档

你可以查看在线阅读文档: http://cocoadocs.org/docsets/JSONModel


基本使用

涉想你的JSON数据像这样:

{ "id": "10", "country": "Germany", "dialCode": 49, "isInEurope": true }
  • 为你的数据模型创建一个Objective-C的类,继承自JSONModel.
  • 将JSON中的keys在.h文件中声明为属性:
#import "JSONModel.h"

@interface CountryModel : JSONModel

@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* country;
@property (strong, nonatomic) NSString* dialCode;
@property (assign, nonatomic) BOOL isInEurope;

@end

在.m文件中不需要做任何事情.

  • 用数据初始化你的model:
#import "CountryModel.h"
...

NSString* json = (fetch here JSON from Internet) ...
NSError* err = nil;
CountryModel* country = [[CountryModel alloc] initWithString:json error:&err];

如果传过来的JSON合法,你所定义的所有的属性都会与该JSON的值想对应,甚至JSONModel会尝试去转换数据为你期望的类型,如上所示:

  • 转换id,从字符串转换为int
  • 只需要拷贝一下country的值
  • 转换diaCode,从number转换为字符串
  • 最后一个是将isInEurope转换为BOOL属性

所以,你所需要做的就是将你的属性定义为期望的类型.


在线教程

官方网站: http://www.jsonmodel.com

在线文档: http://jsonmodel.com/docs/

傻瓜教程:


举个栗子

命名自动匹配

{
  "id": "123",
  "name": "Product name",
  "price": 12.95
}
@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
@end

@implementation ProductModel
@end

模型嵌套 (模型包含其他模型)

{
  "order_id": 104,
  "total_price": 13.45,
  "product" : {
    "id": "123",
    "name": "Product name",
    "price": 12.95
  }
}

@interface OrderModel : JSONModel
@property (assign, nonatomic) int order_id;
@property (assign, nonatomic) float total_price;
@property (strong, nonatomic) ProductModel* product;
@end

@implementation OrderModel
@end

模型集合

{
  "order_id": 104,
  "total_price": 103.45,
  "products" : [
    {
      "id": "123",
      "name": "Product #1",
      "price": 12.95
    },
    {
      "id": "137",
      "name": "Product #2",
      "price": 82.95
    }
  ]
}
@protocol ProductModel
@end
@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
@end

@implementation ProductModel
@end

@interface OrderModel : JSONModel
@property (assign, nonatomic) int order_id;
@property (assign, nonatomic) float total_price;
@property (strong, nonatomic) NSArray<ProductModel>* products;
@end

@implementation OrderModel
@end

注意: 尖括号后 <code>NSArray</code> 包含一个协议. 这跟Objective-C原生的泛型不是一个概念. 他们不会冲突, 但对于JSONModel来说,协议必须在一个地方声明.

key映射

{
  "order_id": 104,
  "order_details" : [
    {
      "name": "Product#1",
      "price": {
        "usd": 12.95
      }
    }
  ]
}

@interface OrderModel : JSONModel
@property (assign, nonatomic) int id;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSString* productName;
@end

@implementation OrderModel

+(JSONKeyMapper*)keyMapper
{
  return [[JSONKeyMapper alloc] initWithDictionary:@{
    @"order_id": @"id",
    @"order_details.name": @"productName",
    @"order_details.price.usd": @"price"
  }];
}

@end

设置全局键映射(应用于所有model)

[JSONModel setGlobalKeyMapper:[
    [JSONKeyMapper alloc] initWithDictionary:@{
      @"item_id":@"ID",
      @"item.name": @"itemName"
   }]
];

设置下划线自动转驼峰

{
  "order_id": 104,
  "order_product" : @"Product#1",
  "order_price" : 12.95
}
@interface OrderModel : JSONModel

@property (assign, nonatomic) int orderId;
@property (assign, nonatomic) float orderPrice;
@property (strong, nonatomic) NSString* orderProduct;

@end

@implementation OrderModel

+(JSONKeyMapper*)keyMapper
{
  return [JSONKeyMapper mapperFromUnderscoreCaseToCamelCase];
}

@end

可选属性 (就是说这个属性可以为null或者为空)

{
  "id": "123",
  "name": null,
  "price": 12.95
}
@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString<Optional>* name;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSNumber<Optional>* uuid;
@end

@implementation ProductModel
@end

忽略属性 (就是完全忽略这个属性)

{
  "id": "123",
  "name": null
}
@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString<Ignore>* customProperty;
@end

@implementation ProductModel
@end

设置所有的属性为可选(所有属性值可以为空)

@implementation ProductModel
+(BOOL)propertyIsOptional:(NSString*)propertyName
{
  return YES;
}
@end

使用JSONModel自带的 HTTP 请求


//add extra headers
[[JSONHTTPClient requestHeaders] setValue:@"MySecret" forKey:@"AuthorizationToken"];

//make post, get requests
[JSONHTTPClient postJSONFromURLWithString:@"http://mydomain.com/api"
                                   params:@{@"postParam1":@"value1"}
                               completion:^(id json, JSONModelError *err) {

                                   //check err, process json ...

                               }];

将model转化为字典或者json格式的字符串


ProductModel* pm = [[ProductModel alloc] initWithString:jsonString error:nil];
pm.name = @"Changed Name";

//convert to dictionary
NSDictionary* dict = [pm toDictionary];

//convert to text
NSString* string = [pm toJSONString];

自定义数据的转换


@implementation JSONValueTransformer (CustomTransformer)

- (NSDate *)NSDateFromNSString:(NSString*)string {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:APIDateFormat];
    return [formatter dateFromString:string];
}

- (NSString *)JSONObjectFromNSDate:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:APIDateFormat];
    return [formatter stringFromDate:date];
}

@end

自定义处理指定的属性


@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSLocale *locale;
@end

@implementation ProductModel

// Convert and assign the locale property
- (void)setLocaleWithNSString:(NSString*)string {
    self.locale = [NSLocale localeWithLocaleIdentifier:string];
}

- (NSString *)JSONObjectForLocale {
    return self.locale.localeIdentifier;
}

@end

自定义JSON校验


@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price;
@property (strong, nonatomic) NSLocale *locale;
@property (strong, nonatomic) NSNumber <Ignore> *minNameLength;
@end

@implementation ProductModel

- (BOOL)validate:(NSError *__autoreleasing *)error {
    BOOL valid = [super validate:error];

    if (self.name.length < self.minNameLength.integerValue) {
        *error = [NSError errorWithDomain:@"me.mycompany.com" code:1 userInfo:nil];
        valid = NO;
    }

    return valid;
}

@end

  • 错误处理
  • 自定义数据校验
  • 自动比较和相等判断
  • 更多.

Misc

作者: Marin Todorov

参与者: Christian Hoffmann, Mark Joslin, Julien Vignali, Symvaro GmbH, BB9z.
任何人都可以 pull requests.

更新log : https://github.com/jsonmodel/jsonmodel/blob/master/CHANGELOG.md

Utility to generate JSONModel classes from JSON data: https://github.com/dofork/json2object


许可

This code is distributed under the terms and conditions of the MIT license.


参考指南

NB! 如果你解决了你发现的某个BUG, 请添加单元测试,这样以便我在合并之前复现这个BUG.


使用问题汇总

1、1.4.0版本的JSONKeyMapper

如果需要替换服务端返回来的key,需要按照下面的结构@{@"你的key":@"接口返回的key"},并且请使用initWithModelToJSONDictionary这个方法。

+ (JSONKeyMapper *)keyMapper {
    return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:
            @{
              @"isChecked":@"ischecked",
              @"tagId":@"tagid",
              @"tagName":@"tagname",
              @"tagValue":@"tagvalue"
              }];
}
2、模型包含模型时的使用, 被包含的模型需要声明protocol

eg:KSAlreadyBuyListModel 包含一个属性KSAlreadyBuyModel, 我们需要将KSAlreadyBuyModel声明protocol,不然会解析失败。

@class StoryModel, AblumModel;

@protocol KSAlreadyBuyModel <NSObject>
@end

@interface KSAlreadyBuyModel : KSBaseModel

@property (nonatomic, strong) StoryModel *storyModel;
@property (nonatomic, strong) AblumModel *ablumModel;

@end

@protocol KSAlreadyBuyListModel <NSObject>
@end

@interface KSAlreadyBuyListModel : KSBaseModel

@property (nonatomic, copy) NSString *contentid;
@property (nonatomic, copy) NSString *contenttype;
@property (nonatomic, copy) NSString *iconurl;
@property (nonatomic, copy) NSString *orderno;
@property (nonatomic, copy) NSString *productid;
@property (nonatomic, copy) NSString *productname;
@property (nonatomic, copy) NSString *realityprice;
@property (nonatomic, strong) KSAlreadyBuyModel *param;

@end
3、如果你在同一个.h中为了解析所有数据,创建了多个model,一定要记得这些model在.m文件中实现他们。eg:上面的第二个。

相关文章

网友评论

  • unhangcorn:请问为什么不推荐使用以下方法?
    +(BOOL)propertyIsOptional:(NSString *)propertyName{
    return YES;
    }
    jueyingxx:@unhangcorn

    NSString *nsPropertyName = @(propertyName);
    if([[self class] propertyIsOptional:nsPropertyName]){
    p.isOptional = YES;
    }
    会把所有的属性都做判断,其实也问题不大,我就这么用的
  • 我本善良:@interface Message : JSONModel

    @property(nonatomic, retain) NSString<Optional> *name;

    @end
    用wcdb的话,加上<Optional>类似这样的关键词,会
    [WCDB][ERROR]Code:2, Type:Abort, Msg:[(null)] should conform to WCTColumnCoding protocol, which is the class of [Message name]
    难道wcdb和jsonmodel不能一起用吗?
    jueyingxx:@我本善良 wcdb我没用过,你可以用YYModel试试
  • 7e89da275b09:一直在用JSONModel,请问下,我的一个类里面各种申明都写好的,返回的数据是全的,解析出来有10条数据,其中有两三条数据是nil,但是解析之前的responseObject是有值的,这个大概是什么原因呢?(这个类是三层数组和模型嵌套)
    jueyingxx:@Avidya
    最大的可能性就是服务端的类型和你声明的类型不匹配了
    jueyingxx:@Avidya
  • a24df6838a47:@property (nonatomic,assign)CGSize
    @property (nonatomic,assign)BOOL
    BOOL和结构体 不能用Optional, 怎么解决
    jueyingxx:@王晓鹏友
    @implementation KSBaseModel
    + (BOOL)propertyIsOptional:(NSString *)propertyName {
    return YES;
    }

    - (id)valueForUndefinedKey:(NSString *)key {
    return @"";
    }
    @end
    jueyingxx:@王晓鹏友 option只针对对象
  • 弹一首键盘协奏曲:{
    "order_id": 104,
    "total_price": 103.45,
    "products" : [
    {
    "id": "123",
    "name": "Product #1",
    "price": 12.95
    },
    {
    "id": "137",
    "name": "Product #2",
    "price": 82.95
    }
    ]
    }
    兄弟。我遇到一个问题。这里面不是嵌套数组么?当products对应的数组返回为空的时候,会崩掉。设置忽略也没用。你遇到过么?
    jueyingxx:@弹一首键盘协奏曲 问题解决就好
    弹一首键盘协奏曲:@jueyingxx 不是model的问题。是后台返回错了,返回的不是json格式的数据,我没有校验。现在解决了,不过还是谢谢你。
    jueyingxx:@弹一首键盘协奏曲 看你model怎么申明的
  • snail小菜:大神在吗?
  • 冰三尺:请问下, 这个JSONModel 可以完美匹配swift 语言的数据解析吗? 由于最近升级了swift 4.1 和xcode9.3 发现以前使用的HandyJSON 会crash, 正在考虑寻找OC版的json解析, 今天试了下MJExtension, 发现它里面解析出来的数组类型是NSArray 和 swift 里面的Array 不匹配, 因为我的数据类型都是Array类型, 不可能全部修改成NSArray, 正在寻找其他的库来解决问题.
    jueyingxx:@里脊糖醋 swift建议是YYModel
  • PGOne爱吃饺子:楼主,你好这个映射是干什么用的
    PGOne爱吃饺子:在使用JSONmodel的时候,我们要实现映射这个东西么
    jueyingxx:映射就是将接口返回的字段,替换成你的Model中的对应的字段
  • 奥美拉唑:请问如果服务器返给我的对象为null,且这个对象应该包含多层数据结构,我该如何附上默认值?例如:
    {
    "code": "AAA",
    "message": "BBB",
    "result": null
    }
    但是正常情况下应该是 :
    {"code":"AAA","message":"BBB","result":{"descrip":"CC","downloadUrl":"DD","forceUpdate":"EE","update":"FFF"}} 求指点。
    奥美拉唑:@jueyingxx 恩恩 已经按照这个方法解决了。谢谢喽
    jueyingxx:@奥美拉唑 把result属性设置为option
  • 俺妈说昵称越长媳妇越漂亮:如果我有个属性.不确定返回的类型,定义为id类型,解析到就会报错....怎么解决?网上搜id类型都是服务器返回带id字段的...
  • Felix灬泡泡:求解:
    在使用JSONModel的时候,如果服务器返回值为:“A”或“B”,我想要在Model类中直接转换为BOOL属性值如何转?(比如当服务器返回值为“A”时,转换为YES,否则转换为NO)
  • a619f7edb5b9:你好!为什么我的这种写法报错呢?@property (nonatomic, strong) NSArray<LXQGoodsOrderModel>*ordersGoodsList; 错误信息type argument 'LXQGoodsOrderModel' must be a pointer (requires a'*') insert '*'
    jueyingxx:@小桥虾米 声明下protocol
  • 楚丶liu香:+(JSONKeyMapper*)keyMapper
    {
    return [[JSONKeyMapper alloc] initWithDictionary:@{
    @"order_id": @"id",
    @"order_details.name": @"productName",
    @"order_details.price.usd": @"price"
    }];
    }
    这里边的key和value映射关系是不是写反了呢,应该是property作为key,json数据对应的key作为value吧
    楚丶liu香:@jueyingxx 了解了,没用过1.3之前的版本~~
    jueyingxx:@楚丶liu香 这都是1.3之前的写法,你可以看文章的最后
    jueyingxx:@楚丶liu香 嗯,没有更新,最新版的反过来即可
  • 默默_David:还是感觉MJExtension好的多
    jueyingxx:@默默_David 只是个工具类,顺手就行
  • 俺妈说昵称越长媳妇越漂亮:有没有办法解析类中类(匿名类)?我想上创建几份.h和.m文件,发现解析不了,有什么办法解决?把类创建出来就可以解析了...
    俺妈说昵称越长媳妇越漂亮:@jueyingxx 就是在在.h中声明了...一份.h和.m文件,里面有有3个模型类,其中一个是 外层的,另外两个是里层的.
    jueyingxx:@俺妈说昵称越长媳妇越漂亮 解析的json,model,至少需要在.h里面申明
    俺妈说昵称越长媳妇越漂亮:有没有办法解析类中类(匿名类)?我想少创建几份.h和.m文件,发现解析不了,有什么办法解决?把类创建出来就可以解析了...
  • 像羽毛那样轻: 有没有针对空值 设置默认值的设置
  • long弟弟:感谢楼主分享,谢谢
  • iOSTbag: JSONModel 数组中的字符串 没有 键怎么解析
  • Timmy_Yang:反馈:二维数组怎么破?Like this: [ [{},{},{}],[{},{},{}],[{},{},{}]]
  • LoveY34:JSONModel支持转化的类型是不是有限制的啊?
    jueyingxx:@LoveY34 暂时没遇到
  • 掘金:请问json嵌套在3层以上,怎么建立model呢
  • Hedgehogembrace:有个问题 当json数据里面的key 是struct系统特定的结构体时,没办法声明成员 是不是可以重写命名?
    xincc:这么横干嘛, 了不起啊, JsonModel是我用过最难用的序列化工具, 没有之一
    Hedgehogembrace:@Hedgehogembrace 比如声明成员变量的时候写成_struct,解析接口json的时候仍然按struct解析。请问这样怎么实现?
  • ShineYangGod:为什么我的模型嵌套模型就一直报错啊?
  • ShineYangGod:我有个问题,就是说后台给我返回的数据中有一个是字典,我在模型里面创建了一个模型字典,为什么一直报错?
    ShineYangGod: @神地创造 就是常见的错误
    jueyingxx:看错误信息
  • 子胥:请教下楼主,如果一个ModelA有个属性数组NSArray<ModelB>* modelB;
    这样的话要依赖ModelB这个文件,如果不想依赖ModelB(因为要解耦),有什么好的方法吗?
    jueyingxx:如果要使用,就必须有关系,如果不使用,不写即可。
    另外这跟解耦没半毛的关系
  • 十一岁的加重:@property (strong, nonatomic) NSArray<ProductModel>* products;
    这条太坑了,还得引入@protocol ProductModel,都没法写成
    @property (strong, nonatomic) NSArray<ProductModel*>* products;

    访问其数组内元素的时候,还是JSONModelArray,每次加入到其他数组都会报错
    addObjectFromArray but argument is not array
    十一岁的加重:@zhaihongxia 换框架 了
    zhaihongxia:在吗,这个问题你是怎么解决的
    十一岁的加重:真没看成JSONModel跟MJExtension和YYModel的优势在哪里,老实说项目中我也在用JSONModel,主要是看到有个NSCopy再结合YYCache可以存储项目中所有的Model,好在项目里一个模型上有个数组属性,这个数组里又放着一堆模型这种情况不多,不多,再搞个全局Model KVO那就只能弃用JSONModel了
  • 星辰流转轮回:写的好详细
  • Draven_Lu:请问怎么把jsonModel对象转换成字典或者数组?
    Draven_Lu:@jueyingxx THX
    jueyingxx:@Draven_Lu
    + (NSMutableArray *)arrayOfDictionariesFromModels:(NSArray *)array;
    + (NSMutableDictionary *)dictionaryOfDictionariesFromModels:(NSDictionary *)dictionary;
    jueyingxx:@Draven_Lu NSDictionary *dict = [indexModel toDictionary];
  • 伦敦乡下的小作家:有个问题想请教一下,我的user类继承jsonmodel,模拟器运行能获取到user数据,真机却获取不到数据,能帮忙分析下错误吗
    jueyingxx:@伦敦乡下的小作家
    - (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err;
    传个err进去看看
  • erero:请教下 如果实体字符串为nsstring 返回的是nil 但是我们要设置为 @“” 应该怎么做。
    jueyingxx:@erero 1、让后台给你直接返回@“”。2、你重写getter方法
  • graliet:问个问题,JSONModel里面建立键的映射关系的方法,红框里面的前后可以互换么,比如吧@id:@"orderId"改成@"orerId":@"id"这样可以么
    jueyingxx:@Graliet
    第一个写你的model类里面声明的,第二个写服务端返回的字段。
    eg:
    @"orderId":@"id"
  • Haley_Wong:影大,重写某属性的set方法,比如属性叫name ,是重写setName:(NSString *)name,还是setNameWithNSString:(NSString *)name呢?发现两个都可以哎,哪个好?
  • 赤子知心:亲 问一下 这样的数据结构,里面类型为nsdictionary,为什么错
    rderDetailDic{
    od = {
    cn = 0;
    id = 1;
    m = 18591925056;
    n = drivername1;
    s = 0;
    sn = "\U7537";
    };
    ord = {
    ct = 1473490442000;
    did = 1;
    id = 116;
    p = 0;
    pa = "";
    pm = 3;
    pmn = "\U7ebf\U4e0b\U652f\U4ed8";
    rid = 727;
    s = 0;
    sn = "\U5df2\U521b\U5efa";
    t = 1;
    tn = "\U666e\U901a\U8ba2\U5355";
    uid = 43;
    };
    ou = "<null>";
    req = {
    ct = 1473490440000;
    i1 = "<null>";
    i2 = "<null>";
    id = 727;
    n1 = "\U897f\U5b89\U4e9a\U6cf0\U6c7d\U8f66\U670d\U52a1\U6709\U9650\U516c\U53f8";
    n2 = "jerry\U9020\U578b";
    s = 3;
    sn = "\U63a5\U5230\U4e58\U5ba2";
    t = 0;
    tn = "\U5b9e\U65f6";
    x1 = 109;
    x2 = 109;
    y1 = 34;
    y2 = 34;
    };
    }
  • Easy_VO:映射是不是不用管数据的嵌套结构?
    jueyingxx:@Easy_逝殤 框架会帮你自动处理的,被包含的model需要声明protocol
  • 8a2694faac8d:亲,我这边有个问题,需要你帮下忙。
    请问,当遇到这种结构的json数据,使用jsonModel该怎样写数据模型?
    {
    "result" : [
    {
    "3" : {
    "midpri" : "1152.00",
    "buypri" : "1146.00",
    "variety" : "美元账户铂金",
    "maxpri" : "1153.00",
    "minpri" : "1142.50",
    "closeyes" : "1145.00",
    "time" : "2016-08-01 10:05:00.0",
    "todayopen" : "1147.00",
    "quantpri" : "1.00",
    "sellpri" : "1158.00"
    },
    "1" : {
    "midpri" : "1350.45",
    "buypri" : "1349.15",
    "variety" : "美元账户黄金",
    "maxpri" : "1351.65",
    "minpri" : "1346.55",
    "closeyes" : "1351.25",
    "time" : "2016-08-01 10:05:00.0",
    "todayopen" : "1350.00",
    "quantpri" : "-2.10",
    "sellpri" : "1351.75"
    },
    "4" : {
    "midpri" : "706.50",
    "buypri" : "700.50",
    "variety" : "美元账户钯金",
    "maxpri" : "710.50",
    "minpri" : "704.50",
    "closeyes" : "708.00",
    "time" : "2016-08-01 10:05:00.0",
    "todayopen" : "709.50",
    "quantpri" : "-7.50",
    "sellpri" : "712.50"
    },
    "2" : {
    "midpri" : "20.56",
    "buypri" : "20.49",
    "variety" : "美元账户白银",
    "maxpri" : "20.60",
    "minpri" : "20.32",
    "closeyes" : "20.35",
    "time" : "2016-08-01 10:05:00.0",
    "todayopen" : "20.35",
    "quantpri" : "0.14",
    "sellpri" : "20.63"
    }
    }
    ],
    "resultcode" : "200",
    "reason" : "SUCCESSED!",
    "error_code" : 0
    }
    XiuQiCloud:@jueyingxx 为什么是错误的,通过xml转成字典出现这种数据结构的情况很多啊?
    XiuQiCloud:@8a2694faac8d 你这种情况找到解决办法没?刚好我这边也有这种数据结构?
    jueyingxx:@8a2694faac8d 你这个很简单啊,问题是你服务端返回的结构有问题
    "2" : {
    "midpri" : "20.56",
    "buypri" : "20.49",
    "variety" : "美元账户白银",
    "maxpri" : "20.60",
    "minpri" : "20.32",
    "closeyes" : "20.35",
    "time" : "2016-08-01 10:05:00.0",
    "todayopen" : "20.35",
    "quantpri" : "0.14",
    "sellpri" : "20.63"
    }这个2是多余的
  • Raybon_lee:亲,有个问题,需要和你交流一下,当数据为嵌套类型的时候,数组包含字典,这个时候解析的model 是字典,还需要再次转化,有遇到过吧
    ```
    {
    "order_id": 104,
    "total_price": 103.45,
    "products" : [
    {
    "id": "123",
    "name": "Product #1",
    "price": 12.95
    },
    {
    "id": "137",
    "name": "Product #2",
    "price": 82.95
    }
    ]
    }
    ```
    jueyingxx:@Raybon_lee 你姿势不对,数组中的每个dict转个model

    {
    "order_id": 104,
    "total_price": 103.45,
    "products" : [
    {
    "id": "123",
    "name": "Product #1",
    "price": 12.95
    },
    {
    "id": "137",
    "name": "Product #2",
    "price": 82.95
    }
    ]
    }

    @protocol ProductModel
    @EnD

    @interface ProductModel : JSONModel
    @property (assign, nonatomic) int id;
    @property (strong, nonatomic) NSString* name;
    @property (assign, nonatomic) float price;
    @EnD

    @Implementation ProductModel
    @EnD

    @interface OrderModel : JSONModel
    @property (assign, nonatomic) int order_id;
    @property (assign, nonatomic) float total_price;
    @property (strong, nonatomic) NSArray<ProductModel>* products;
    @EnD

    @Implementation OrderModel
    @EnD
    Raybon_lee:@jueyingxx 文档看过了,那个我尝试了几种类型,这个就是元数据,但是他这个没有示例,只要是包含数组就会有问题,如果是字典转换没问题
    jueyingxx:@Raybon_lee 你说的是模型嵌套,完全可以满足,建议会直接看官方的英文文档

本文标题:iOS中JSONModel的使用

本文链接:https://www.haomeiwen.com/subject/iuloxttx.html