Convert NSArray into array of JSON objects - ios

I'd like to create a JSON array of objects from the resultsArray.
NSMutableArray *resultsArray = [NSMutableArray array];
FMResultSet *resultsSet = [database executeQuery:queryString];
while ([resultsSet next]) {
[resultsArray addObject:[resultsSet resultDictionary]];
}
For clarification, I'm using FMDB to query a database. I'm then storing the resulting objects within the resultsArray. From here I want to convert that results array into a JSON array of objects.

You can use NSJSONSerialization class to create a JSON file from your dictionary using the class method
NSData * JSONData = [NSJSONSerialization dataWithJSONObject:resultsArray
options:kNilOptions
error:&error];
For more info look at apple documentation

Related

How to parse NSDictionary sequentially?

I need to parse a json and get the key value pairs in the same sequence as they are present in response.
Currently what i'm doing is
-(instancetype)initWithJson:(NSDictionary *)responseDict {
if (self = [super init]){
NSArray *tempArray = [[NSArray alloc] init];
NSArray *roomSizesForAcArray = [responseDict valueFromDictionaryWithNSNullCheck:#"roomSizesForAc"];
NSArray *loadChartForInverterArray = [responseDict valueFromDictionaryWithNSNullCheck:#"loadChartForInverter"];
if(roomSizesForAcArray && roomSizesForAcArray.count>0){
self.isInverterChart=false;
tempArray=roomSizesForAcArray;
}
else if(loadChartForInverterArray && loadChartForInverterArray.count>0){
self.isInverterChart=true;
tempArray=loadChartForInverterArray;
}
self.arrayOfChartSizeObjects=tempArray;
if(tempArray && tempArray.count>0){
//Temp array first object is a dictionary which i need to parse sequentially
self.arrayOfKeys = [[tempArray objectAtIndex:0] allKeys];
//This array of keys is random every time and not sequential
}
}
return self;
}
I need to someway parse the dictionary [tempArray objectAtIndex:0] maintaining the order of keys in init.
Not clear what you want, you want dictionary while you are already parsing the dictionary. To get dictionary from the JSON use below code.
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:receiveData options:kNilOptions error:&error];
To get all the keys and then retrieve the details use
NSArray *sortedKeys = [[jsonDict allKeys]
Once you have keys then get the details
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}
Dictionaries are unordered collections. You say "...maintaining the order of keys in init". There is no such thing.
JSON "Objects", the JSON equivalent of a NSDictionaries/Swift Dictionaries, have the same issue.
Some JSON libraries will preserve the order in which key/value pairs are submitted to be sent, but you should not depend on that. The JSON protocol does not guarantee it.
Once you receive JSON data and convert it to an NSDictionary/Dictionary, the order in which the key/value pairs is sent is lost. The only way I know of to preserve the (already unreliable) order of the key/value pairs from the original JSON data stream is to parse the JSON yourself rather than deserializing it using NSJSONSerialization.
If you want your data in a particular order, you should use an array as the container object to send it. You can send an array of key/value pairs if you need to.

Creating a json object from nsmutable array

I have got three nsmutablearray imageNameArray,imageSizeArray,baseArray.
I have to create a json of following type.
{
"documents": [
{
"file_size": 48597,
"file_name": "pisa-en.pdf",
"file_content": "base64String"
}
]
}
since the number of elements within document array might vary, Im trying to create nsdictionary from arrays as follows,
for (int i = 0; i< [_imageNameArray count]; i++){
[dictionary setValue:self.imageNameArray[i] forKey:#"file_name"];
[dictionary setValue:self.imageSizeArray[i] forKey:#"file_size"];
[dictionary setValue:self.baseArray[i] forKey:#"file_content"];
}
but it is not creating the json of required type. When Im trying to print it, there exists an equals to symbol between key and value.
No need to check in console that it is equal symbol or colon. If you want to send data to server then first convert it in data like,
NSDictionary *dict ; // your dict or array
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
It will convert it in colon (:) instead of =.
And if you are using AFNetworking then you not need to do this jsonserialization, you can directly pass dictionary or array as parameter in method and afnetworking manage all things.
Hope this will help :)

How to get the no. of objects in JSON Data?

If i am saving my data in NSDictionary "dict"
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
How can i know that how many objects i am having in seasons, i know how to save NSArray and it's count but it's not an array actually. and all question i saw on stackoverflow they all are using array object.
{ "seasons":{
"Season 0":{ },
"Season 1":{ }
}
NSDictionary has a count method:
NSInteger count = [dict[#"seasons"] count]; // Returns 2
Try This It will give the array of values / keys
[dict allValues]; or [dict allKeys]

Getting one value from JSON API in Objective-C

I'm trying to get one value from JSON. JSON is located in NSString and it looks like this:
{"coord":{"lon":-122.38,"lat":37.57},"weather":[{"id":300,"main":"Drizzle","description":"Lekka mżawka","icon":"09d"}],"base":"stations","main":{"temp":304.74,"pressure":1017,"humidity":35,"temp_min":300.15,"temp_max":307.59},"visibility":16093,"wind":{"speed":6.7,"deg":250},"clouds":{"all":75},"dt":1437346641,"sys":{"type":1,"id":478,"message":0.0615,"country":"US","sunrise":1437311022,"sunset":1437362859},"id":5357155,"name":"Hillsborough","cod":200}
I'm interested in getting "temp". How should I do that?
Assuming your JSON string was stored as a NSString named JSONString:
NSError *error;
NSDictionary *keys = [NSJSONSerialization JSONObjectWithData:[JSONString dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&error];
NSLog(#"temp = %#", keys[#"main"][#"temp"]); // temp = 304.74
To get the main sub item in weather, which is an array with multiple items, you should point out its index to tell the selector which object in the array is the one you are looking for. In this case, it's 0:
NSLog(#"weather = %#", keys[#"weather"][0][#"main"]); // weather = Drizzle

Parse json Data in iOS

I know it's a common question, but I am stuck with is API
How to Parse data from this API : http://dl.bahramradan.com/api/1/get/ig
it contain 20 Object and in every object there are 3 other Objects called "image",date" and "caption"
how can I store all "date" values in an NSMUtableArray in ios?
I did this :
NSString *urlStr = [NSString stringWithFormat:#"http://dl.bahramradan.com/api/1/get/ig"];
NSURL *url = [NSURL URLWithString:urlStr];
NSData *json = [NSData dataWithContentsOfURL:url];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:json options:0 error:NULL];
NSArray *dateArray = [dict objectForKey:#"date"];
But when I run my app, it crashs on the last line, what is wrong ?
I did not check, if your JSON is valid. But there is one obvious mistake in your code: If the JSON consists of 20 objects, I assume those being contained in an array, rather than in a dict!
So first thing to change is
NSArray *array = [NSJSONSerialization JSONObjectWithData:json options:0 error:NULL];
Then, you want to extract the 'date' values for all items and combine these in another array.
Easiest way to achieve that, is by using a KVC Collection Operator
NSArray *dateArray = [array valueForKeyPath:#"#unionOfObjects.date"];
So, what '#unionOfObjects.date' does, is: going through all the objects in the array, look for each of their 'date' value and combine them in the returned array.
Check out this excellent post about KVC Collection Operators!

Resources