I have a NSArray of custom objects (only NSString, NSArray, NSNumber) and I need to send this JSON to the server. Using NSJSONSerialization throws an error because it is not a property list.
Is there any other way, except manually creating a NSString object in JSON format?
NSString *manualPost = [NSString stringWithFormat:#"{\"key1\": \"%#\",\"key2\": \"%#\",\"key3\": %#,\"keyArray4\": [%#]}", val1, val2, val3, valArray4];
To close this question, right answer is using dictionary and values can be NSArrays, NSNumbers, NSStrings - in other words - Property List.
Sample:
NSDictionary *postDictionary = #{#"key1": #"value1",
#"key2": #(1),
#"key3":#[#"key3", #(5.9)]
};
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSLog(#"PostData %#", postData);
NSLog(#"Error: %#", error);
Related
I am making this app that gets some data from the url (censored). The problem is that I didn't found a solution to get what the PHP script echo.
A normal returned array from that script looks this:
{"user_data": {"id":"78","image":"https://www.i********p.com/uploads/ideas/fun/2017/03/28/78.jpg","idea":"Join Facebook groups related to your passions or hobbies and meet friends.","owner_ID":"1","owner":"Eduard","owner_photo":"https://www.i********p.com/uploads/members/1/1.png","rating":"4","reviews":"1 review","msg":"success"}}
The question is how can I access each value of this array from "user_data" using Objective-c (without a loop)?
The Objective-c code:
- (void)getJSON {
NSError *error;
NSString *url_string = [NSString stringWithFormat: #"https://www.app.i******o.com/getidea.php?topic=%#", ideasTopic];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error) {
NSLog(#"Something went wrong: %#", error);
} else {
NSLog(#"json: %#", json);
NSLog(#"IMAGE: %#", [[json getObjectAtIndex:0] getObjectForKey:#"image"]);
}}
Objective-C supports literal version to access dictionary. You can directly access values by using keys.
NSString *imageUrl = json[#"user_data"][#"image"];
Your json is a dictionary of dictionaries. json[#"user_data"] returns a dictionary with keys and values. You can access values for this dictionary through respective keys. json[#"user_data"][#"image"] gives you required value for respective key.
Edit:
You need to change your json variable type to NSDictionary too.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
The JSON text you provided is deserialized into NSDictionary object (you can check it yourself, by looking up what class a json variable has in your example).
So to get what you want (ex. image), you simply write
json["user_data"]["image"]
my app get data from a php web service and return a NSString
["first name","last name","adress","test#test","000-000-0000","password","code","0"]
How can i get the second element ?
This is a JSON formatted string which you are getting from your web service.
You must be getting bytes from server. Just replace your variable which have bytes stored with my variable "response data".
Code:
NSError* error;
NSArray* myResultArray = [NSJSONSerialization
JSONObjectWithData:responseData options:kNilOptions error:&error];
You will get an array in variable "myResultArray" and you can get all value by index.
Code:
NSString* first name = [myResultArray objectAtIndex:0];
What you have given here is an array and not a string. May be you could provide more details like the exact response and the code that you are trying here.
To Convert a JSON string to NSDictionary all you need to do is:
NSError *jsonError;
NSData *objectData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:nil
error:&jsonError];
And to NSArray :
NSArray *array = [NSJSONSerialization JSONObjectWithData:objectData options:nil error:&jsonError];
NSString *secondElement = array[1];
That web service doesn't return an NSString. It runs data in some format defined by the service, and you convert it to an NSString. Find out what the format actually is, then convert it appropriately, for example using NSJSONSerialization.
The example string your showed here seems wired. This looks more like a array than string. If this is a NSArray then you can do it like this:
NSArray *data = #[#"first name",#"last name", #"adress", #"test#test", #"000-000-0000", #"password", #"code", #"0"];
NSLog (#"Second component = %#", data[1]);
However, if you anticipate this as NSString then this is how you would handle this:
NSString *test = #"[\"first name\",\"last name\",\"adress\",\"test#test\",\"000-000-0000\",\"password\",\"code\",\"0\"]";
NSLog (#"Second component = %#", [test componentsSeparatedByString:#","][1]);
I am new to iOS. I have this JSON data that I needed to parse:
{
"allseries":[
{
"type":"HR",
"title":"Heart Rate",
"xLabel":"Time",
"yLabel":"Beats per Min",
"defaultUnit":"BPM",
"url":"info/info?user=admin%40korrent.com&type=HR",
"size":18,
"firstTs":1406755651,
"lastTs":1406841254
},
{
"type":"TEMP",
"title":"Temperature",
"xLabel":"Time",
"yLabel":"Temperature",
"defaultUnit":"F",
"url":"info/info?user=admin%40korrent.com&type=TEMP",
"size":6,
"firstTs":1406854147,
"lastTs":1406854283
}
],
"status":"OK"
}
So far this is my code:
NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(#"--> async response data (string): %#", dataReceived);
NSData *jsonData = [dataReceived dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&jsonError];
NSLog(#"JSON key and value %#", [dict description]);
NSLog(#" %# ", dict[#"allseries"]);
NSString *jsonString=dict[#"allseries"];
if (_programState == 4){
NSLog(#"state is 4");
NSLog(#"%#",jsonString);
NSData *Data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
However, the code throws invalid argument exception for this line:
NSData *Data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
Further more, jsonString seems totally "inoperable". I cannot split it, append strings to it etc. So what's wrong?
// The following two lines are just for logging and otherwise are not needed.
NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(#"--> async response data (string): %#", dataReceived);
// Deserialize the JSON data into a dictionary
NSError *jsonError;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: _responseData options:nil error:&jsonError];
NSLog(#"JSON key and value %#", dict);
// Get the array from the dictionary element "allseries".
NSArray *jsonArray = dict[#"allseries"];
NSLog(#"jsonArray: %#", jsonArray);
Here jsonArray is the array of dictionaries for "allseries" from the JSON
What you did is totally, totally wrong.
dict[#allseries] is not an NSString. It is an NSArray with two elements, and both its elements are NSDictionary.
I'm new to JSON and don't understand why this is failing. The JSON is valid according to on-line validation tools, but NSJSONSerilization says this the string is invalid. Why is it invalid?
NSString* JSON = #"{\"Questionnaire\":{\"questionnaireid\":1,\"modifiedDate\":\"2012-12-28 15:27:00\"}}";
if (![NSJSONSerialization isValidJSONObject:JSON]) {
return nil;
}
NSError *jsonParsingError = nil;
NSDictionary* data = [NSJSONSerialization dataWithJSONObject:JSON options:NSJSONReadingMutableContainers error:&jsonParsingError];
why you did serialization when you already created JSON yourself ?
What you should do:
NSData *jsonPayload = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:jsonPayload
options:kNilOptions error:&error];
Because a JSON Object must be of type NSArray or a NSDictionary while you are passing a NSString.
From the docs:
An object that may be converted to JSON must have the following
properties:
The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.
UPDATE
You probably want to do this:
NSData *jsonData = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
quite new to iOS development and objective-c at the same time. I have the following method:
-(NSMutableArray *)fetchDatabaseJSON{
NSURL *url = [NSURL URLWithString:#"http://www.ios.com/ios/responseScript.php"];
NSError *error = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:&error];
//jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//NSLog(#"Array: %#",[jsonArray objectAtIndex:0]);
jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Dictionary: %#", jsonDictionary);
return jsonArray;
}
Now the NSLog shows this:
2013-02-03 19:15:37.081 TestConnection[24510:c07] Dictionary: (
Bannana,
Apple,
SomeCheese )
From what I understand that whatever is inside the dictionary doesn't have key-value. How can this be? and how can I fix it? I want to be able to have keys to ease operations on dictionary.
Regards,
JSONObjectWithData may return an NSArray or NSDictionary, depending on the JSON data you give it. If your JSON string is an array, you will have an NSArray. If your JSON data is a dictionary, you will get an NSDictionary.
Convert your JSON data (your data variable) to string and print it out with NSLog. To convert NSData to NSString, use something like:
NSString *myString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
If you print it out and see a JSON array, you simply don't have a dictionary there.. If you can alter the server-code that generates the JSON, you may be able to change that.
One more thing I noticed, you assume that the returning container is mutable. If I'm not mistaken, you need to use an option like NSJSONReadingMutableContainers in the options parameter of JSONObjectWithData to get that.
One last tip, if you want to check in code if you have an NSArray (or NSDictionary), use something like:
if ([obj isKindOfClass:[NSArray class]]) {...}