My web service api (POST) has a parameter that takes a dictionary object like this
void MyMethod (Dictionary<string, List<string>> myDictionaryParam);
Basically, the keys are strings and the values are an array of strings.
How do i send this data from Objective C.
So far, i have tried the following.
NSMutableDictionary* dataDictionary = [[NSMutableDictionary alloc] init];
[dataDictionary setObject:personIds forKey:"firstKey"];
[dataDictionary setObject:personIds forKey:#"secondKey"];
NSDictionary* dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:dataDictionary, #"myDictionaryParam", nil];
NSError* seralizationError;
NSData* data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&seralizationError];
The API gets the dictionary, but the dictionary has 0 key/value pairs.
Don't worry about how to post json data..I got that part covered. I am interested in knowing how to post an actual dictionary object from Objective C
Related
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.
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
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!
I have an app that is requesting a users list of followers. I would like to be able to change some of the data inside of the array I am getting back from twitter, but I can't seem to get it to become a proper mutable copy.
Here is my code:
NSMutableDictionary *theData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
NSMutableDictionary *TWData = [[NSMutableDictionary alloc] init];
TWData = [theData mutableCopy];
NSMutableArray *data = [TWData objectForKey:#"users"];
The order this is in and doing a mutable copy FIRST is the last thing I tried. This is the code that throws an error:
[[data objectAtIndex:2] setObject:#"indeed" forKey:#"following"];
And here is the typical error message:
[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
I understand WHY it is giving me the error, my question is how can I make EVERYTHING (all child dictionaries and array, and all of their child dictionaries and array, etc.) mutable so I can alter the data.
Any help is great, thanks!
You can use CFPropertyListCreateDeepCopy from Core Foundation:
NSMutableDictionary* mutableData = (NSMutableDictionary*) CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFPropertyListRef) theData, kCFPropertyListMutableContainers));
See the CFPropertyList reference for more info. In particular, the Property List Mutability Options can be used to control what is mutable in the returned copy.
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"];