So my JSON request should look something like:
{
"MyDictionary" : ["some values"],
"RegularValue" : "regularValue",
}
So what I currently have done is:
NSDictionary *myDict = #{#"Blah" : #"1", #"Yadayada" : #"2"};
NSDictionary *jsonDict = #{"MyDictionary" : myDict, "RegularValue" : "someValue"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:&error];
So this works fine. The problem I have is, instead of manually creating MyDictionary, what I want to do is use a custom sublcass of NSObject and serialize that to JSON. I basically have to manually create the NSDictionary for the properties of my custom NSObject and put that in the NSJSONSerialization method. But I was wondering if there was a better way to do this? Thanks.
maybe this can help JLCustomClassDisassembler.
it iterates the custom object to get the properties. this will give you dictionary/array then just use sbjson/jsonkit or what ever you prefer to construct your json string.
To achieve this you would need to create your own custom NSObject class with attributes and more and still have a custom method to serialize the object, similar to the way toString works on java, on Objective-C you would need to implement
- (NSString *)description
on your method and then return the serialized object.
on this method you could read all the attributes of the current object and then somehow serialize them, this thread presents a nice sample code to read all the attributes of a certain Object
Get an object properties list in Objective-C
Related
In my iPhone App.
Problem: When I am trying to get the value from dictionary in model class it is giving me the nil values.
Why this is happening, is this the memory management issue ?
I did this,
I am passing NSDictionary, from my viewController to NSMutableArray Category and from that I am passing it to my Modelclass.
If you want to see the coding,
In my ViewController.m file
[arrayNews convertToNewsArticles];
In my NSMutableArray category I am calling method convertToNewsArticles.
for(NSMutableDictionary *dictionary in self) {
NewsArticle *newsArticle=[[NewsArticle alloc] initWithDictionary:dictionary];
[arrayConverted addObject:newsArticle];
}
I am talking about this dictionary that I am passing.
Here is my Model class
-(NewsArticle*)initWithDictionary:dictionary{
self.title=dictionary[#"title"];
self.author=dictionary[#"author"];
self.urlString=dictionary[#"url"];
return self;
}
Update:
I solved by using IAModelBase class on GitHub.IAModelBase
If it is subclass of NSMutableArray then you can add object like,
[self addObject:newsArticle];
in your for loop and return self will return your final mutable array and you can use it as per desired need!
And refer Apple documentation for more detail. You have to implement some mandatory methods if you want to subclass the NSMutableArray.
When I was trying to convert NSDictionary Objects to Model Objects.
I could not pass the whole dictionary to Model class. Like mentioned in the question.
But instead I used,
IAModel classes
Read the readme file.
Also see the 1st Issue,it is solved.
Pull Issue
In my JSON response i receive a dictionary, which has a array, inside that array is a dictionary with few key-values, to make it simple to understand here is the JSON response:
{
weather = (
{
description = haze;
icon = 50n;
id = 721;
main = Haze;
}
);
}
I want to know how can i retrieve the elements description, icon, id and main. Suppose i have a NSString called str, how can i add the value of description to this string. I have tried many different things, but none seem to work. The one i thought should work, but didn't is:
str = [[[dir valueForKey:#"weather"] objectAtIndex:0] valueForKey:#"description"];
Can someone let me know how can i access those 4 values. I don't want to create a new array of those values and then retrieve them. Regards.
Use NSJSONSerialization to convert your JSON data to NSObjects.
Then you need to index into your objects based on their structure.
If the structure is fixed, and guaranteed, you can do it with fixed indexes/keys:
//data in theJSONDict.
NSArray *outerArray = theJSONDict[#"weather"];
NSDictionary *firstWeatherItem = outerArray[0];
NSString *firstItemDesc = firstWeatherItem[#"description"];
You could also do it all in 1 line:
firstItemDesc = theJSONDict[#"weather"][0][#"description"];
But that is much harder to debug.
If this is JSON data coming from a server you need to code more defensively than above, and write code that tries to fetch keys from dictionaries, tests for nil, and either loops through the array(s) using the count of objects, or tests the length of the array before blindly indexing into it. Otherwise you'll likely crash if your input data's format doesn't match your assumptions.
(BTW, do not use valueForKey for this. That is KVO code, and while it usually works, it is not the same as using NSArray and NSDictionary methods to fetch the data, and sometimes does not work correctly.)
I am importing a json where the objects have many array attributes such as images:
"images": [
"model1.jpg",
"model2.jpg"
],
"models": []
"one model",
"another model",
"third model"
]
Currently I just do:
[ExampleObject MR_importFromArray:objectArrayFromJson];
but these arrays break this auto import since it can't auto fit NSArray to NSData (the binary from when setting the model up in Xcode).
Is there anyway to modify the Model class files (like custom setters/getters) so the MagicalRecord can import my array and store it in the entitys´ attribute and when I retrieve it I get an NSArray in return?
I solved this myself after some research and I want to share it to whoever might get stuck with same problem.
My problem was that I wanted to save an NSArray into an entity attribute of type NSData. To be able to do this with MagicalRecord I needed to implement a method in my NSManagedObject m-file like this:
- (BOOL) importImages: (id) array {
NSData *imagesData = [NSKeyedArchiver archivedDataWithRootObject:array];
self.images = imagesData;
return YES;
}
so import<;attribute-name without ;> the method must be called.
EDIT:
According to this page you return YES if your code process the data. Return NO if you want MagicalImport to continue processing the attribute and use the default import routines.
I am trying to write a method which will allow me to keep the order of my NSMutableDictionary keys when they are being inserted into the data structure. I know that the NSMutableDictionary works of a hash map, hence not maintaining specific order.
So I need to somehow keep track of the keys which are being inserted into the dictionary, and when retrieving the values from the dictionary, the keys are to be printed(key values) in this same order as when originally inserted. The keys which are inserted into the dictionary are alphanumeric. They just need to be printed out in the same order as when inserted into the NSMutableDictionary.
Can this be achieved? I would like to remain using the NSDictionary Data Structure.
NSDictionary (and all its relations) are unordered collections so to "keep its order" makes no sense as there is no order.
If you are wanting to retrieve objects in a specific order then you need to be using an NSArray. (Or NSOrderedSet if uniqueness of hashes is important).
Simple and naive option
If you have a dictionary structure of...
{
key1:value1,
key2:value2,
key3:value3,
//and so on
}
Then you might be better using something like...
[
{
key1:value1
},
{
key2:value2
},
{
key3:value3
}
]
// i.e. an array of dictionaries
More code but much better option
Or you could create a new collection class as a subclass of NSObject.
In the class you could have something like...
- (void)addObject:(id)object forKey:(id)key
{
self.dictionary[key] = object;
[self.array addObject:key];
}
And...
- (id)objectForKey:(key
{
return self.dictionary[key];
}
And...
- (id)objectAtIndex:(NSUInteger)index
{
return self.dictionary[self.array[index]];
}
And even...
- (void)removeObjectForKey:(id)key
{
[self.dictionary removeObjectForKey:key];
[self.array removeObject:key];
}
You could even make it conform to fast enumeration so you can do...
for (id object in mySuperSpecialCollection) {
}
and make it dispense objects in the order of the array.
Can this be achieved? I would like to remain using the NSDictionary Data Structure.
No. When using instances of NSDictionary the actual class is private. As often with class clusters, it's not possible to subclass NSDictionary and use derived functionality (storing key value pairs).
The best way to go is to set up your own data structure, maybe using an NSOrderedSet and an NSDictionary in conjunction.
for an iOS 5.0 application using ARC, i have an NSArray of objects that contain NSArray of other objects within it. Is it possible to extract a list of objects from inner arrays without iterating through the Array e.g. say, with NSpredicate or valueForKeyPath. To be clearer, I have:
NSArray *objtype1 contains
-id
-NSArray *imageObjs containing imageObjects
-imagetype = 1 <--1st imageObject
imageURL1
-imagetype = 2 <--2nd imageObject
imageURL2
-NSArray *objtype2
-other parameters
I need to extract the NSArray of imageType = 1 imageObjects to pass in for further processing. Is this possible? (I'm looking at NSpredicate, and valueForKeyPath, but have not found anything yet)
I think the reason you haven't found anything yet is because it's not there. You could implement your own category on NSArray to use predicates recursively. Perhaps someone else have done it already. I don't know.
Ummmmm it seems a bit unclear as to what you are doing. It looks like you have an NSArray of multiple types. And you want the imageObjs array inside it.
If you infact have an NSArray like this, it would be monumentally easier to convert it to an NSDictionary. Then you can use [dictionary valueForKey:#"Image Array"]; to get the image array out of it.
Currently, your solution to get the imageObjs array would be [objtype1 objectAtIndex:1]; then iterate over that array to use the imageObjects in it.
for(ImageObject *obj in arr) {
//do stuff
}