JSONModel: json to array? - ios

Is it possible to parse json to an array of JSONModel objects using JSONModel? Like parse json below:
[{"id" : 1}, {"id" : 2}]
to two JSONModel objects having property of "id".

You should use arrayOfModelsFromDictionaries: on your model class like so:
NSArray* models = [YourModelClass arrayOfModelsFromDictionaries: objects];
This will go over "objects" and convert each dictionary to a model and you get the result in models. If any item in objects fail to convert to model "models" will be nil.
Here's the class docs for this method:
http://jsonmodel.com/docs/Classes/JSONModel.html#//api/name/arrayOfModelsFromDictionaries:

Why not trying BWJSONMatcher?
First you should declare your own data model:
#interface MyDataModel : NSObject
#property (nonatomic, assign) NSInteger id;
#end
Then you can easily get your array with BWJSONMatcher within one line:
NSArray *jsonArray = [BWJSONMatcher matchJSON:jsonString withClass:[MyDataModel class]];
Hope this could help you.

Related

Serialize JSONModel - How to convert custom object to JSON in iOS?

How to serialize a custom object with JSONModel ?
#property(nonatomic,strong) NSString<Optional> * tag_post_type;
#property(nonatomic,strong) NSString<Optional> * tag_users_type;
#property(nonatomic,strong) NSArray<Optional> * tags;
#property(nonatomic,strong) NSMutableArray<TagMediaModel*>* tag_posts;
#property(nonatomic,strong) NSMutableArray<TagLocationModel*>* locations;
I try to create a JSON file out of my custom Object with the JSONModel framework for iOS. I get the Error:
EXCEPTION: Invalid type in JSON write (TagMediaModel)
When I call toJSONString Method, I got this issue.
[tagAutomaticModel toJSONString];
This is the model data:
locations = (
"<TagLocationModel> \n [id]: 780307344\n [name]: Hotel Central Park, india\n</TagLocationModel>",
"<TagLocationModel> \n [id]: 463004401\n [name]: Miraj Cinema new year\n</TagLocationModel>",
"<TagLocationModel> \n [id]: 246187965\n [name]: Surya Treasure Island asia\n</TagLocationModel>",
);
"tag_posts" = (
"<TagMediaModel> \n [media_code]: BS0tQeFhU_Z\n [media_id]: 1492016420475981785\n [media_url]: https://scontent.cdninstagram.com/t51.2885-15/e15/17881459_...\n [media_type]: I\n</TagMediaModel>"
);
#property(nonatomic,strong) NSMutableArray<TagMediaModel>* tag_posts;
made few change as above, just removed the star in TagMediaModel.
The angle brackets after NSMutableArray contain a protocol. As #R.Mohan said, you need to remove * pointer and use without pointer.
The protocol must be in place. So add #protocol tag_posts and #protocol locations at top in respective class.
EXCEPTION: Invalid type in JSON write (TagMediaModel) I guess you are converting json to your custom class one or more times. Do it only once. It will resolve your problem.

How I can get average number of array`s element, when array doesn`t have only integer type data?

I have array with 3 data types: NSString(Employe's name) NSString(Employee's last name) and int(salary). This elements created by constructor:
-(void) addEmployeeWithName:(NSString *)employeesName andLastName:(NSString *) employeesLastName andSalary:(int)employeesSalary;
I need to count average salary using another method, how I can do it?
definition of array:
#property(strong, nonatomic) NSArray<Employee *> *employees;
method which add object to array:
-(void) addEmployeeWithName:(NSString *)employeesName andLastName:(NSString *)employeesLastName andSalary:(int)employeesSalary
{
Employee *myEmp =[[Employee alloc] initWithFirstName:employeesName lastName:employeesLastName salary:employeesSalary];
[self.employees addObject:myEmp];
}
You can call the KVC method valueForKeyPath: with attribute #avg on the array
NSNumber *average = [self.employees valueForKeyPath:#"#avg.salary"];
NSLog(#"%ld", average.integerValue);

RestKit NSDictionary mapping NULL values

I have a mapped object which have this property:
#interface SynchObj : NSObject
#property (nonatomic, copy) NSDictionary *fields;
#end
mapped as
mappingDict = #{ #"fields" :#"fields",};
responseMapping = [RKObjectMapping mappingForClass:[SynchObj class]];
[responseMapping addAttributeMappingsFromDictionary:mappingDict];
But when the server send a dictionary like this
{
name:null
surname:null
}
the mapping produces a dictionary with these values:
name : "<null>"
surname : "<null>"
I would like to have "" instead of "". Is it possible?
You should be able to use KVC validation which RestKit supports to verify / edit the value before it is set. If you implement validateValue:forKey:error: on your destination class (SynchObj) you can verify and edit the value being set for any key (you would need to iterate the keys and values of the dictionary).

How to serialize an array of Core Data objects into an array of string using RestKit?

I am currently using RestKit version 0.20.3 in my iOS project to communicate with my backend web service.
In some cases, my web service returns an array of tags (django-taggit) in string format and I needed to map each tag string into a core data entity.
// example JSON from web service
"response" : { "tags": ["tag1", "tag2", "tag3"] }
// example Core Data entities
#interface TagEntity : NSManagedObject
#property (nonatomic, retain) NSString *tagName;
#end
From the below discussion, I found a way to map an array of tag strings into core data objects.
https://groups.google.com/forum/#!topic/restkit/54eZFQIjl7c
tagEntityMapping = [RKEntityMapping mappingForEntityForName:#"TagEntity" inManagedObjectStore:[RKManagedObjectStore defaultStore]];
[tagEntityMapping addPropertyMapping:[RKAttributeMapping mappingFromKeyPath:nil toKeyPath:#"tagName"]]
tagEntityMapping.identificationAttributes = #[#"tagName"];
[resultEntityMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"tags" toKeyPath:#"tags"withMapping:tagEntityMapping]];
Now, I am looking for a way to post an array of tag strings from Core Data objects to web service.
In other words, given that I have an array of TagEntity Core Data objects, I wish to send an array of [TagEntity tagName]
To achieve this, I used [resultEntityMapping inverseMapping] as a request mapping, but as result, I get
"request" : { "tags": [{"tag1": {}}, {"tag2": {}}, {"tag3": {}}] }
while what I really wish to get is
"request" : { "tags": ["tag1", "tag2", "tag3"] }
I would appreciate any help. Thanks!
If you just have an array of TagEntity instances then you can get the array of strings with:
NSArray *tagStrings = [tags valueForKey:#"tagName"];
Once you have that you can pass the array to RestKit (wrapped into an NSDictionary based on your sample JSON) or use NSJSONSerialization directly and use the underlying AFNetworking provided API to send the JSON.

Parsing JSON in iOS, inner dictionaries

I am new to JSON and iOS, I have some json data that I want to load into an array,
This is the json data
{
"items": [
{
"name": "abc",
"description": "cheeseburger",
},
{
"name": "def",
"description": "ostrichburger",
},
{
"name": "zxc",
"description": "sh1tjustgotreal",
},
{
"name": "scfs",
"description": "mylifeforaiur",
}
]
}
Now I keep on getting dictionaries with dictionaries? Why is that?
On another note, If I can modify the structure of this json cos I really just want to access the inner nodes ( abc, def ) what would I change in it to make it simpler for me and others to use it? Can I get rid of the "items" node?
When the data on the sender's end is structured as a collection of named fields, you get back a dictionary for each group of named fields. In this particular case, it looks like the outermost object has one field, which is a collection (i.e. a list or an array) of objects that each have a name and description. In other words, the sender sends you something like this:
#interface Item
#property (readwrite, copy) NSString* name;
#property (readwrite, copy) NSString* description;
#end
#interface MyObject
// This array contains objects of type Item
#property (readwrite) NSArray *items;
#end

Resources