How to create class classes (NSObject) automatically from a json dictionary?

Is there a way to create model classes (wrapper) of a dictionary or json responce? because there are a lot of web services in my application and all WSs contain big data. if I create all the time one by one, it takes a lot of time to create an NSObject Class with null data validation and an Encode-Decode Object. or please suggest me to correctly create all NSObjects manually? I can not make out the direct dictionary. Thanks.

+6
source share
3 answers

Finally, I got a very simple and fast Model class generator tool for iOS and Android . just copy and paste your answer and get the Model Class from the tool.

  • Download JSON Accelerator from the AppStore (Mac AppStore).
  • Copy your JSON response from the browser (the response must be confirmed by JSON).

  • Paste into Json Accelerator -> Click "Create and Save with Your Model Name."

  • Select Display Language and add the base class name . (Class prefix is ​​not required)
  • See the following class classes and submodel classes (these are Automaticallyy Generate All JSON Object Classes)


Use like this β†’> For example, your JSON Respoce dictionary

{"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]} 
  • create an Array Employee, and then create an Object With Created Model Classes, as shown below, and you should use For loop or enumerateObjectsUsingBlock any to create and then Add to Mutable Array.

    NSArray * arrTemp = [NSArray arrayWithArray: yourResponceDict [@ "employees]]; NSMutableArray * myMutableArray = [NSMutableArray array];

     [arrTemp enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { Employee *aObj = [Employee modelObjectWithDictionary:obj]; [myMutableArray addObject:aObj]; }]; 

This tool is very simple and saves time for creating Json object classes for data analysis anywhere in the development.

+3
source

For this purpose, you can use modules such as BaseModel, ObjectMapper, or EVReflection for open source projects. These are all open source modules that you can use in your project.

+2
source

Have you looked at NSKeyValueCoding ? It has several methods that may be useful to you, including the following, which can set all the values ​​for an object based on the dictionary representation of the object.

[object setValuesForKeysWithDictionary:dictionary];

Assuming that you can somehow determine the class of an object from a dictionary view, you can use it; In addition, you can easily turn objects into dictionaries using dictionaryWithValuesForKeys:

0
source

All Articles