Objective-C deserialize JSON into objects using JSONModel

核能气质少年 提交于 2019-12-25 19:00:45

问题


Is there a way using JSONModel library without inherit the JSONModel class.

I want to deserialized JSON to Objective C class without inherit form JSONModel.

Is there another library that deserialized JSON into objects without inheritance?


回答1:


You don't have to use a library for JSON Serialization in iOS. From iOS 5.0 onwards there is a class NSJSONSerialization is available for doing this. https://developer.apple.com/library/ios/documentation/foundation/reference/nsjsonserialization_class/Reference/Reference.html

Consider this code for converting list of contacts to json string

+(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;
}

Hope this helps. (I gave ios specific answer because tags are related to iOS.




回答2:


From iOS5 onwards you can use NSJSONSerialization class for serializing as well as deserializing. For deserialization, you want to first convert your json string to an NSData object, and call the class method JSONObjectWithData

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

Using isKindOfClass you can find out if this is an dictionary or array because JSONObjectWithData will return either an NSDictionary or an NSArray, depending whether your JSON string represents an a dictionary or an array.




回答3:


Why wouldn't you want to inherit from JSONModel?

The thing is that when you inherit from JSONModel you are inheriting all the tools of the library. It's intended to be used like that because the methods that the library exposes are not static so you need to have instances derived from JSONModel.



来源:https://stackoverflow.com/questions/22979946/objective-c-deserialize-json-into-objects-using-jsonmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!