I get an error while I send Json data to server. I used the following code to change the NSMutableDictionary To JSON.
NSString* jsonString1 = [postDict JSONRepresentation];
NSLog(#"%#",jsonString1);
JSON Format:
{"user_email":"gupta.nivrit#gmail.com","firstname":"nivrit","user_password":"1234","confirm_passward":"1234"}
I use the following method to send this JSON format to server:
NSMutableDictionary *responseDict =
(NSMutableDictionary *)[[mWebServiceHelperOBJ
makeCallToURL:#"register.php"
withDataPost:jsonString1] JSONValue];
When I implemented this code I received this issue
incompatible pointer type sending NSString to parameter of type NSMutableDictionary.
If your method
- (NSString *)makeCallToURL:(NSString*)url withDataPost:(NSMutableDictionary*)dict;
is the same as in this question: Uploading PDF file through JSON Web Service, then the JSON encoding of the request data is done inside
that method, so you should call it directly with the postDict,
and not with the JSON string jsonString1:
NSMutableDictionary *responseDict =
(NSMutableDictionary *)[[mWebServiceHelperOBJ makeCallToURL:#"register.php"
withDataPost:postDict] JSONValue];
(This assumes that postDict is an NSMutableDictionary.)
Related
I am having a ton of trouble accessing a string in a dictionary, called json. This comes back from a server in an API call. The key that I am trying to access is "Message".
Some reason the console shows that I am retrieving a dictionary in "Errors", but when I try to access this value the app crashes.
How do I appropriately get and store the key "Message" and the value " The old password does that match our records"?
CODE:
//json is the dictionary I successfully retrieve from an API call (see picture)
DLog(#"feed response = %#", json);
NSDictionary *errorsDictionary;
//CRASHES ON THE NEXT LINE
errorsDictionary = [[NSDictionary alloc]initWithDictionary:[json objectForKey:#"Errors"]] ;
NSString *message = [[NSString alloc]initWithFormat:#"%#",[errorsDictionary objectForKey:#"Message"]];
NSLog(#"The dictionary is%#", errorsDictionary);
Console log:
Errors contains an array, the message is the value for key Message of the first item.
NSString *message = json[#"Errors"][0][#"Message"];
NSLog(#"The message is %#", message);
I am sending a JSON encoded POST type to a server of mine which reads the sent information in PHP and decodes it there. Now when I re-encode it and send it back it works perfectly and I can NSLog the response but my issue is how do I get a specific section of the response?
Here is an example response:
responseString: {"status":"ok","code":0,"original request":{"username":"test"
`,"password":"test"}}`
Suggestions, thoughts?
What you are receiving is actually a 'dictionary of objects'. You can separate the data in the above code as follows:
First, serialize the response data using JSON serialization as follows:
NSError* error;
NSDictionary* responseDictionary = [NSJSONSerialization JSONObjectWithData:returnData options:nil error:&error];
You may then separate the dictionary as you wish.For instance, if you want to retrieve the value for "status", you may use:
NSString *status = [responseDictionary objectForKey:#"status"];
Or, if you want to retrieve "original request" which is another dictionary, you may use:
NSDictionary *originalRequest = [responseDictionary objectForKey:#"original request"];
Hope this helps!
The response received from the server is JSON data.
Here is an excellent tutorial on JSON parsing for iOS and there are plenty of tutorials & docs if you browse.
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
In JSON, "{}" represents a dictionary and "[]" is an array. So, try this
NSDictionary* originalRequest = [responseString objectForKey:#"original request"];
you can dig in further like this,
NSString* username = [originalRequest objectForKey:#"username"];
I strongly recommend you to read some tutorials on JSON.
We have to create a Jason file to send to server .
The way i found to do that is this :
NSDictionary* dic = #{#"Username" :userName,
#"Firstname" :firstName,
#"Lastname" : lastName,
#"Email" : email,
#"Password" : pass,
};
NSData* json = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
I dont really understand why after creating the dic , which is already a Json file, I have to use the NSJSONSerialization when creating the NSData ? ,why not just set the dic to the NSData ? What exactly this serialization do ?
Also ,why don't create just an NSString that will contain this structure ?
dic is an Objective-C dictionary (a collection of key-value pairs) and has nothing to do with JSON. Printing the dictionary might look similar to JSON, but it isn't.
NSJSONSerialization creates JSON data from the dictionary. JSON is a text format and is documented e.g. here: http://www.json.org. The JSON data for your dictionary would look like this:
{"Firstname":"John","Email":"jon#apple.com","Username":"john","Lastname":"Doe","Password":"topsecret"}
That NSJSONSerialization creates NSData and not NSString is just a design decision of the author of that class. You can convert the data to a string with
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
I'm learning Xcode at the moment and i have a project that is pulling data from a Mysql database using php and passing it to my app via json. In the database all varchars are set to utf8_bin.
here is the php:
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo json_encode($this->Idea_model->get($id));
here is a snipet of the outputted JSON:
[{"id":"1","title":"JWT blood sucka","objective":"test ","mission":"test","design_time":"80","development_time":"80","votes":"0","user_id":"0","date_created":"2012-08-03","date_modified":"2012-08-03","active":"1"},{"id":"2","title":"ford - liveDealer","objective":"to increce ","mission":"thid id a es","design_time":"80","development_time":"80","votes":"1","user_id":"1","date_created":"0000-00-00","date_modified":"0000-00-00","active":"1"}]
in xcode I'm using this function to pull in the JSON [reference tutorial:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5]
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:#"loans"]; //2
NSLog(#"loans: %#", latestLoans); //3
}
when i use this JSON file from the tutorial it works
http://api.kivaws.org/v1/loans/search.json?status=fundraising
but when i use my JSON file i get the following error.
[8690:207] -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x6a10400
Current language: auto; currently objective-c
obviously there is an issue with my JSON output as i printed the contents from the tutorial file in my PHP file and that worked as well.
i also have tried "reset contents and settings" in the iOS simulator.
any ideas?
The returned object appears to be an array but your code is treating it like a dictionary (json object/hash)
The error tells you this: it say that the message objectForKey: (which is a method on NSDictionary) is being sent to an instance of __NSCFArray, which is an implementation class of NSArray, hence my supposition...
Yes I have an Idea -
-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x6a10400
Arrays are not dictionaries. They do not respond to objectForKey
They respond to objectForIndex;
You are thinking you have an array when you have a dictionary.
Common JSON mistake.
Heres your data:
its a list
starts here --> "[" then the object starts here "{"
[{"id":"1","title":"JWT blood sucka","objective":"test ","mission":"test","design_time":"80","development_time":"80","votes":"0","user_id":"0","date_created":"2012-08-03","date_modified":"2012-08-03","active":"1"}
then a comma "," then the next item in the list starting with a { "{"id":"2","title":"ford - liveDea
JSON says a list is an array and an object is a dictionary so flip your code around
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSArray* latestLoans = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSLog(#"loans: %#", latestLoans); //3
for (int i=0; i < latestLoans.count; i++)
{
NSDictionary *myLoan = (NSDictionary*)[latestLoans objectAtIndex:i];
NSLog(#"loan:%#", myLoan);
}
....
Got it?
I have a great framework however I cannot figure out how to create requests. All the tutorials assume you are simply downloading and parsing Json data - but I need to build a Json request send it off and then parse the response.
Anyone have ideas and in particular sample code which builds up the request.
The framework doesn't handle NSObject but NSDictionary seems to work:
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"value1", #"key1", #"value2", #"key2", nil];
NSString *requestJson = [jsonDictionary JSONRepresentation];
NSLog(#"requestJson %#", requestJson);
In this JSON framework...you can use the JSONRepresentation method on NSDictionary and NSArray.....
You should download JSON lib, then import header:
#import "NSObject+SBJSON.h"