Gson equivalent in Objective-C

后端 未结 8 1452
我寻月下人不归
我寻月下人不归 2021-02-05 09:14

Is there any equivalent to gson in Objective-C?

Thanks.

8条回答
  •  醉梦人生
    2021-02-05 09:59

    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];
    

提交回复
热议问题