JSON creation in objective c, invalid JSON - ios

I am creating a JSON to be sent in service on checking online its showing error:
Error: Parse error on line 1:
[{\ "SAHExpertCode\"
--^ Expecting 'STRING', '}', got 'undefined'
My JSON is [{\"SAHExpertCode\" : \"\", \"ShiftType\" : \"AM\", \"LocFunId\" : \"CLT0004218\", \"SAHQualCode\" : \"CA\" }]
Please tell me what's wrong and how to correct it.First i am making JSON filterString = [{ "SAHExpertCode" : "", "ShiftType" : "AM", "LocFunId" : "CLT0004218","SAHQualCode" : "CA" }] on checking found it is correct then creating a dictionary NSDictionary*dictData=#{#"MbrId":[USER_DEFAULTS valueForKey:#"MemberId"],#"StrFilter":[NSString stringWithFormat:#"%#",filterString],#"shiftCrtlNos":shftCntrlNmbrs}; NSMutableArray *finalArray = [[NSMutableArray alloc]init]; [finalArray addObject:dictData]; NSString *finalString =[self ConvertArrayToJsonData:finalArray];finalString = [finalString stringByReplacingOccurrencesOfString:#"\n" withString:#""]; finalString = [finalString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];after creation of final string it is generating symbol \ for JSON Conversion my code is -(NSString *)ConvertArrayToJsonData:(NSMutableArray *)array{ NSError error;
NSData jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; NSString *JSONString; if (!jsonData) { NSLog(#"error :%#",error); } else {JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding]; // NSLog(#"jsonstring:%#",JSONString);
}
return JSONString;
}
//i need JSON like [ { "StrFilter" : "[ { \"SAHExpertCode\" : \"\", \"ShiftType\" : \"PM\", \"LocFunId\" : \"CLT0004218\", \"SAHQualCode\" : \"CA\" }]", "MbrId" : "MBR0000035", "shiftCrtlNos" : "0080013526,0080014697" }] also tell me how to remove \ from String

i replaced the unwanted \ symbols by doing
finalString = [finalString stringByReplacingOccurrencesOfString:#"\" withString:#""]; in the JSON string.

I suggest you go to www.json.org and look at the correct formatting of JSON data. And the easiest way to get correctly formatted JSON is to create an array or dictionary that you want to convert to JSON, and use NSJSONSerialization to do the job.

Just use default NSJSONSerialization method of iOS
in below example i have a "postMenuArray" which I'm converting in JSON.
NSData * postMenuSerial = [NSJSONSerialization dataWithJSONObject:postMenuArray options:0 error:nil];
NSString *Menujson = [[NSString alloc] initWithBytes:[postMenuSerial bytes] length:[postMenuSerial length] encoding:NSUTF8StringEncoding];
Here I got JSON response
Menujson = [Menujson stringByReplacingOccurrencesOfString:#" "withString:#""];
Lastly I remove all the spacing .
Still facing issue try this
Menujson = [Menujson stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Related

Get values from NSDictionary

Hi I'm new to iOS development. I want to get response and add those values to variable.
I tried it but I'm getting below response. I don't understand why there is slashes in this response.
#"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]"
I tried this :
- (void) sendOtherActiveChats:(NSDictionary *) chatDetails{
NSLog(#"inside sendOtherActiveChats");
NSLog(#"otherDetails Dictionary : %# ", chatDetails);
NSString *VisitorID = [chatDetails objectForKey:#"VisitorID"];
NSString *ProfileID = [chatDetails objectForKey:#"ProfileID"];
NSString *CompanyID = [chatDetails objectForKey:#"CompanyID"];
NSString *VisitorName = [chatDetails objectForKey:#"VisitorName"];
NSString *OperatorName = [chatDetails objectForKey:#"OperatorName"];
NSString *isocode = [chatDetails objectForKey:#"isocode"];
NSLog(#"------------------------Other Active Chats -----------------------------------");
NSLog(#"VisitorID : %#" , VisitorID);
NSLog(#"ProfileID : %#" , ProfileID);
NSLog(#"CompanyID : %#" , CompanyID);
NSLog(#"VisitorName : %#" , VisitorName);
NSLog(#"OperatorName : %#" , OperatorName);
NSLog(#"countryCode: %#" , isocode);
NSLog(#"------------------------------------------------------------------------------");
}
Can some one help me to get the values out of this string ?
You are getting Array of Dictionary in response, but your response is in string so you convert it to NSArray using NSJSONSerialization like this way for that convert your response string to NSData and after that use that data with JSONObjectWithData: to get array from it.
NSString *jsonString = #"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
Now loop through the array and access the each dictionary from it.
for (NSDictionary *dic in jsonArray) {
NSLog(#"%#",[dic objectForKey:#"VisitorID"]);
... and so on.
}
First you need to parse your string.
NSString *aString = #"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]";
NSData *data = [aString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",[[json objectAtIndex:0] objectForKey:#"VisitorID"]);
So you have JSON string and array of 2 objects. So write following code
This will convert JSON string to Array
NSData *myJSONData = [YOUR_JSON_STRING dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSMutableArray *arrayResponse = [NSJSONSerialization JSONObjectWithData:myJSONData options:NSJSONReadingMutableContainers error:&error];
Now use for loop and print data as
for (int i = 0; i < arrayResponse.count; i++) {
NSDictionary *dictionaryTemp = [arrayResponse objectAtIndex:i];
NSLog(#"VisitorID : %#",[dictionaryTemp valueForKey:#"VisitorID"]);
NSLog(#"ProfileID : %#",[dictionaryTemp valueForKey:#"ProfileID"]);
NSLog(#"CompanyID : %#",[dictionaryTemp valueForKey:#"CompanyID"]);
NSLog(#"VisitorName : %#",[dictionaryTemp valueForKey:#"VisitorName"]);
}
Now there are good chances that you will get NULL for some keys and it can cause in crash. So avoid those crash by using Null validations.

Escaped double-quotes appear in string during debugging

I have a dictionary and I need to generate a JSON string by using NSMutableArray. Here is my code:
NSDictionary *dict = #{
#"From":From,
#"To":To,
#"DepartureDate":DepartureDate,
};
[FinalArray addObject:dict];
Then I generate the JSON String like this:
NSError *error;
NSData * JSONData = [NSJSONSerialization dataWithJSONObject:FinalArray
options:kNilOptions
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
NSLog(#"jsonData=%#", jsonString);
Now output is on NSLog like this:
[
{
"From": "city",
"To": "city",
"DepartureDate": "20160301"
}
]
But while I'm debugging, at a breakpoint, the string appears with escaped double-quotes:
"[{\"From\":\"city\",\"To\":\"city\",\"DepartureDate\":\"20160301\"}]"
Why is that?
That's a stringified json object. My guess is that to allow the json to be shown in the console it's stringified, adding the escaped quotes. In your runtime the backslashes don't exist, they are only there to correctly display the json in the console.

How to parse JSON data from textual file in Objective-C

I know, JSON parsing questions are asked over and over again, but still I can't find any answer to this one.
I've been trying to read and parse a textual JSON file using NSJSONSerialization to no avail.
I've tried using the same JSON data from a NSString and it did work.
Here's the code:
NSError *error;
NSString *jsonString1 = [NSString stringWithContentsOfFile:jsonFilePath
encoding:NSUTF8StringEncoding
error:&error];
NSData *jsonData1 = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject1 = [NSJSONSerialization JSONObjectWithData:jsonData1
options:0
error:&error];
NSString *jsonString2 = #"{\"key\":\"value\"}";
NSData *jsonData2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject2 = [NSJSONSerialization JSONObjectWithData:jsonData2
options:0
error:&error];
- The text file contains one line: {"key":"value"}
- jsonString1 = #"{"key":"value"}"
- jsonString2 = #"{\"key\":\"value\"}"
- jsonData1 is 23 bytes in size
- jsonData2 is 15 bytes in size
- jsonObject1 is nil and I get error code 3840
- jsonObject2 is a valid dictionary
Seems like the problem is with reading the file, since the NSStrings and NSDatas differ, but what am I doing wrong here and how can I fix it?
Most likely you file contains some unprintable characters (e.g. \0) that trigger the failure. Printing the error message will tell you at what position the first invalid characters occurs.
For example, try printing "{\"key\":\u{0000}\"value\"}" and you'll seem to get a valid JSON, however decoding it fails.
I always do a check on the return value when doing anything with NSUTF8StringEncoding and if nil, then try NSASCIIStringEncoding:
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (jsonString == nil) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
}
return jsonString;

Converting NSString to proper JSON format

Converting NSString to proper JSON format..
NSString *input_json = [NSString stringWithFormat:#"{\"id\":\"%#\",\"seconds\":\"%d\",\"buttons\": \"%#\"}", reco_id, interactionTime, json_Buttons];
Here json_Button is in json format converted from nsdictionary..
My input_json result is:
{"id":"119","seconds":"10","buttons": "{
"update" : "2",
"scan" : "4"
}"}
It is not in a proper JSON format. key buttons contain "{}" I want to remove these quotes.
Expected Result is:
{
"id": "119",
"seconds": "10",
"buttons": {
"update": "2",
"scan": "4"
}
}
You are going about this all wrong. First, create an NSDictionary that contains all of the data you want converted to JSON. Then use NSJSONSerialization to properly convert the dictionary to JSON.
Something like this will work:
NSDictionary *dictionary = #{ #"id" : reco_id, #"seconds" : #(interactionTime), #"buttons" : json_Buttons };
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if (data) {
NSString *jsonString = [[NSString alloc] intWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
} else {
NSLog(#"Unable to convert dictionary to JSON: %#", error);
}
It's a bad idea to try to build JSON strings manually. Use the NSJSONSerialization class. That makes it easy. Create your dictionary, then call dataWithJSONObject:options:error:.
If you use options: NSJSONWritingPrettyPrinted it inserts line breaks and whitespace that makes the JSON more readable.
By using that function you get correctly formatted JSON every time, and it's flexible because if you send it a different dictionary you get different JSON.

how to remove the \ character

I have a string with the following information:
\"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]\"
and I need to delete the character \ I'm trying to remove as follows, but the character is using the system and leaves close the line of code
NSString *filtered = [[[restConnection stringData] componentsSeparatedByString:#"\"] componentsJoinedByString:#""];
NSLog(#"filtrado: %#", filtered);
the error is
Expected ']' in this part : componentsSeparatedByString:#"\"]
Its looks like JSON data, instead interfering into JSON, just convert JSON string to NSData and then into NSDictionary or NSArray
NSString *jsonString = #"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *array = [NSArray arrayWithArray:json];
Now if you do following NSLog statement
NSLog(#"%#",[[json firstObject] objectForKey:#"CodRTA"]);
Result would be another NSDictionary.
{
CodRTA = 1;
MenssRTA = messaje error;
Resp = "";
}
Btw, I formatted your JSON response, its look like this,
Someting like that
string = [string stringByReplacingOccurrencesOfString:#"\\" withString:#""];
use this code
NSString *str=#"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]";
NSString *filtered = [[str componentsSeparatedByString:#"\\"] componentsJoinedByString:#""];
NSLog(#"filtrado: %#", filtered);

Resources