Object Mapping library from JSON to NSObjects

前端 未结 5 2002
别那么骄傲
别那么骄傲 2021-02-04 08:39

I am trying to build a parser/objectMapper that will build Objective C objects for the JSON I consume from a REST service.

I took some inspiration from RestKit by having

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-04 09:19

    I tried the same approach also. My main problem was, to describe the types accurately. For example for nested arrays I used something like this:

    @{ @"friends" : @[[Person class]] }
    

    But things became messy, because I needed to invent more and more special syntax for different types, that I wanted to support. In the end I stopped pursuing this approach and went for another solution - also because the runtime checks I needed to do were slowing the transformation down.

    There are a lot of solutions out there right now. I would suggest to have a look at Awesome iOS website. And I also would like to point out JSON Class Generator, because it allows you to

    • describe your types accurately (special mappers for date etc. are included),
    • the types are automatically checked (mismatches reported and fallback values provided),
    • you don't need to spend time for writing repetitive code (and the generated code seems to always "just work")

    I hate to advertise, but this tool saved me a lot of work, that I invested into other features of my apps. It came out a little late, now that the world seems to switch to Swift, but even more reason to not waste time on writing models in Objective-C.

    Here are some code examples converting to/form JSON:

    // converting MyClass <-> NSDictionary
    MyClass       *myClass = [MyClass myClassWithDict:someJsonDictionary];
    NSDictionary *jsonDict = [myClass toDict];
    
    // converting NSDictionary <-> NSData
    NSDictionary *someJsonDictionary = [NSDictionary api_dictionaryWithJson:someJsonData];
    NSData *jsonData = [someJsonDictionary api_toJson];
    

    The features mentioned in a previous comment are also supported by JSON Class Generator:

    -isEqual, -hash, -description, -copy, NSCoding/NSSecureCoding/NSKeyedArchiver
    

    support for free and does check for missing/additional/NSNull/optional fields and wrong types in the JSON response, reports errors, gracefully fails with fallback values and does this using method dispatch rather than runtime type introspection (which is faster).

提交回复
热议问题