Is there any equivalent to gson in Objective-C?
Thanks.
DCKeyValueObjectMapping https://github.com/dchohfi/KeyValueObjectMapping is not a JSON parser but an object-json mapper to inject NSObject properties from NSDictionary/NSArray.
I recently used Mantle which works great and is very similar to GSON (which is use for android projects)
In Objective-C the functionality of GSON is sort of built in. Say I have a class defined like so:
@interface MyModel : NSObject
@property(nonatomic,strong) NSString *name;
@property(nonatomic,strong) NSString *address;
@end
And lets say that I have a JSON object defined like so
{
"name":"marc",
"address":"1234 Some Street"
}
Then I can use AFNetowrking to get an NSDictionary of the JSON object which is pretty easy. Finally you can just do a loop like so where dict is the dictionary returned by AFNetworking parsing the JSON and self is an instance of MyModel.
for (NSString *key in dict) {
[self setObject:dict[key] forKey:key];
}
In Java GSON uses reflection to achieve the same effect as the above loop. Its just a lot easier in objective-c so no need for a library to do it. If you have nested objects maybe AFNetworking with DCKeyValueObjectMapping.
OCMapper is very similar to Gson and easy to use https://github.com/aryaxt/OCMapper
Json
{
"firstName" : "FirstName",
"lastName" : "LastName",
"age" : 26,
"dateOfBirth" : "01/01/2013",
"address" : {
"city" : "San Diego",
"country" : "US"
},
"posts" : [
{
"title" : "Post 1 title",
"datePosted : "04/15/2013",
},
{
"title" : "Post 2 title",
"datePosted : "04/12/2013",
}
]
}
Model
@objc public class User: NSObject {
var firstName: String?
var lastName: String?
var age: NSNumber?
var dateOfBirth: NSDate?
var address: Address?
var posts: [Post]?
}
Usage Swift
let user = ObjectMapper.sharedInstance().objectFromSource(dict, toInstanceOfClass:User.self) as User
or
let User = User.objectFromDictionary(dictionary)
Usage Objective C
User *user = [[ObjectMapper sharedInstance] objectFromSource:dictionary toInstanceOfClass:User.class];
or
User *user = [User objectFromDictionary:dictionary];
At WWDC 2017, Apple has introduced the new feature in Swift to parse JSON without any pain using Swift Codable protocol
struct YourStructure: Codable {
let name: String?
let avatarUrl: URL?
private enum CodingKeys: String, CodingKey {
case name
case avatarUrl = "avatar_url"
}
}
decoder:
let decoder = JSONDecoder()
parsedData = decoder.decode(YourStructure.self, from: YourJsonData)
encode:
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(data)
more info: Encoding and Decoding Custom Types
OCMapper is the best i know and the easiest library and it have reverse mapping as well and map complex objects without the need of configuration , and work with realmObjects as well
I think I have found few libraries which can server this purpose but most important one seems to be RestKit