问题
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