Gson equivalent in Objective-C

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

Is there any equivalent to gson in Objective-C?

Thanks.

8条回答
  •  迷失自我
    2021-02-05 09:55

    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.

提交回复
热议问题