Creating a json object from nsmutable array - ios

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 :)

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.

Convert NSArray into array of JSON objects

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

object returned from NSJSONSerialization can vary

Is the following statement correct, or am I missing something?
You have to check the return object of NSJSONSerialization to see if it is a dictionary or an array - you can have
data = {"name":"joe", "age":"young"}
// NSJSONSerialization returns a dictionary
and
data = {{"name":"joe", "age":"young"},
{"name":"fred", "age":"not so young"}}
// returns an array
Each type has a different access method which breaks if used on the wrong one.
For example:
NSMutableArray *jsonObject = [json objectAtIndex:i];
// will break if json is a dictionary
so you have to do something like -
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers error:&error];
if ([jsonObjects isKindOfClass:[NSArray class]])
NSLog(#"yes we got an Array"); // cycle thru the array elements
else if ([jsonObjects isKindOfClass:[NSDictionary class]])
NSLog(#"yes we got an dictionary"); // cycle thru the dictionary elements
else
NSLog(#"neither array nor dictionary!");
I had a good look thru stack overflow and Apple documentation and other places and could not find any direct confirmation of the above.
If you are just asking if this is correct or not, yes it is the safe way to process jsonObjects. It's also how you would do it with other API that returns id.

NSDictionary filled with JSON data

I call an URL that returns me JSON (I use JSONKit). I convert it to a NSString that is this way:
[{"name":"aaaaaa","id":41},{"name":"as","id":23},...
And so on. I want to fill an UIPickerView with only the "name" part of the JSON. But, when the user selects a name, i need the "id" parameter, so i've thought to fill a NSDictionary with the JSON (setValue:id for key:name), so i can get the value picked by the user, and get the id from the dictionary. how could I fill an array with only the "name" of the JSON?
Im a bit lost with the JSONKit library, any guidance? Thank you.
First of all I don't think that its a good idea to have name as key in a dictionary, since you can have many identical names. I would go for id as key.
Now, what you could do is:
NSString *myJson; //Suppose that this is the json you have fetched from the url
id jsonObject = [myJson objectFromJSONString];
// Now you have an array of dictionaries
// each one having 2 key/value pairs (name/id)
NSArray *names = [jsonObject valueForKeyPath:#"name"];
NSArray *ids = [jsonObject valueForKeyPath:#"id"];
// Now you have two parallel arrays with names / ids
Or you could just iterate your json object and handle the data yourself:
for (id obj in jsonObject)
{
NSString *name = [obj valueForKey:#"name"];
NSNumber *id = [obj valueForKey:#"id"];
// Do whatever you like with these
}

iOS : JSON String to NSArray not working as expected

How to parse a a JSON string in iOS app? Using SBJSON. Running the code below. Getting data is successful but the count on the number of entries in the array is zero even tho the JSON string contains entries. My question is how query the JSON string in a loop?
Thanks!
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://safe2pee.org/api/proxlist.php?location=37.7626214,-122.4351661&distance=1"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"string equal = %#", json_string);
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON b objects
NSArray *bathrooms = [parser objectWithString:json_string error:nil];
NSLog(#"count = %d", [bathrooms count]);
// Each element in bathrooms is a single bathroom
// represented as a NSDictionary
for (NSDictionary *bathroom in bathrooms)
{
// You can retrieve individual values using objectForKey on the bathroom NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [bathroom objectForKey:#"name"], [[bathroom objectForKey:#"lat"] objectForKey:#"long"]);
}
It's because it's not working. That's not a valid JSON string. That's 2 JSON dictionaries, back to back, with a comma in between. It's missing the wrapping []. If you actually test the result value of -objectWithString:error:, you'd see it's nil, and if you pass in an NSError** to the error parameter there, you'd get back an error message telling you it's invalid JSON.
I looked at the JSON string returned when I request the URL in your post, and it looks like it is being improperly truncated by the server. The JSON string returned contains a dictionary structure containing, among other things, a key called "bathrooms" whose value is an array of dictionary structures. Each of those bathroom dictionary structures contains several fields including "bid", "name", "lat", ..., "directions", and "comment".
When I scroll to the end of the JSON I received, I see a complete dictionary structure under the "bathrooms" array ("bid" is "MTIyIFMyUA==", "name" is "Momi Tobi's". That dictionary structure contains its closing brace but the closing "]" for the array is missing and the closing "}" for the top-level dictionary structure is missing.
You should look to the service to see why it is returning invalid JSON strings. Once you have a valid string it looks like you should be starting with an NSDictionary and parsing it something like this:
NSDictionary *result = [parser objectWithString:json_string error:nil];
NSArray *bathrooms = [result objectForKey:#"bathrooms"];

Resources