-1

有没有办法使用 JSONModel 库而不继承 JSONModel 类。

我想将 JSON 反序列化为 Objective C 类而不继承 JSONModel。

是否有另一个库将 JSON 反序列化为没有继承的对象?

4

3 回答 3

2

您不必在 iOS 中使用库进行 JSON 序列化。从 iOS 5.0 开始,有一个类NSJSONSerialization可用于执行此操作。 https://developer.apple.com/library/ios/documentation/foundation/reference/nsjsonserialization_class/Reference/Reference.html

考虑使用此代码将联系人列表转换为 json 字符串

+(NSString*) jsonStringRepresentationOfSelectedReceiptients:(NSArray*) contactsList {
      NSMutableArray* contactsArray = [[NSMutableArray alloc]init];
      for (ContactObject *contactObj in contactsList) {
            NSDictionary* ltPair = @{@"phone_no": [NSNumber numberWithLongLong:contactObj.phoneNo, @"email_id": contactObj.emailId, @"display_name": contactObj.displayName]};
            [contactsArray addObject:ltPair];
      }
      NSData *jsonData=[NSJSONSerialization dataWithJSONObject:contactsArray options:NSJSONWritingPrettyPrinted error:nil];
      NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
      NSLog(@"json string: %@", recptJson);
      return jsonString;
}

希望这可以帮助。(我给出了 ios 的具体答案,因为标签与 iOS 相关。

于 2014-04-10T06:46:24.943 回答
1

从 iOS5 开始,您可以使用 NSJSONSerialization 类进行序列化和反序列化。对于反序列化,您需要先将您的 json 字符串转换为 NSData 对象,然后调用类方法 JSONObjectWithData

NSData *jsonData = [myJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&error];

使用 isKindOfClass 您可以确定这是字典还是数组,因为 JSONObjectWithData 将返回 NSDictionary 或 NSArray,具体取决于您的 JSON 字符串代表字典还是数组。

于 2014-04-10T07:16:54.713 回答
0

为什么不想从 JSONModel 继承?

问题是,当您从 JSONModel 继承时,您将继承该库的所有工具。打算这样使用它,因为库公开的方法不是静态的,因此您需要从 JSONModel 派生实例。

于 2014-04-10T06:39:40.660 回答