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);
Related
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.
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];
I have the following json,
{
"method":"login",
"data":{
"username":"abc",
"password":"123"
}
}
I'm using following code to parse it,
NSString* loginMethod= json[#"method"];
NSString* credentials= json[#"data"];
NSLog(#"credentials %#",credentials);
I'm able to get the value for the key data but I'm not be able to get the value of username and password. How to get those values?
change
NSString* credentials= json[#"data"];
to
NSDictionary* credentials= json[#"data"];
then
NSString *username = credentials[#"username"];
if json is in respose data then
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:request.responseData options:kNilOptions error:&err];
if json is in string then
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]; options:kNilOptions error:&err];
NSString* loginMethod= [jsonDic objectForKey:#"method"];
NSString* usename= [[jsonDic objectForKey:#"data"]objectForKey:#"username"];
NSString* password= [[jsonDic objectForKey:#"data"]objectForKey:#"password"];
You could get those values by credentials[#"username"] and credentials[#"password"].
do like
reason it deverives like nested Dictionry
NSString* loginMethod= json[#"method"]; // this is correct
NSString* username= json[#"data"][#"username"];
NSString* password= json[#"data"][#"password"];
Choice -2
NSString* loginMethod= json[#"method"];
// This isNested Dictionary so Do like
NSDictionary* temp= json[#"data"];
NSString *username = temp[#"username"];
NSString * password = temp[#"password"];
I am converting JSON data in to NSString using below code:
NSString *json_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data AS STRING %#", json_string);
it returns NSString in this format:
Data AS STRING
{
"success": true,
"terms": "https://currencylayer.com/terms",
"privacy": "https://currencylayer.com/privacy",
"timestamp": 1446673809,
"source": "USD",
"quotes": {
"USDAED": 3.672993,
"USDAFN": 64.980003,
"USDALL": 127.164497,
"USDAMD": 474.480011,
"USDANG": 1.790326,
"USDAOA": 135.225006,
"USDARS": 9.536025,
"USDAUD": 1.398308,
"USDAWG": 1.79,
"USDAZN": 1.04625,
"USDBAM": 1.800851,
"USDBBD": 2,
"USDBDT": 78.666946,
"USDBGN": 1.80115,
"USDBHD": 0.37727,
"USDBIF": 1562.5,
"USDBMD": 1.00005,
"USDBND": 1.403198,
"USDBOB": 6.899293,
"USDBRL": 3.80025,
"USDBSD": 0.999335,
"USDBTC": 0.002372,
"USDBTN": 65.495003,
"USDBWP": 10.55195,
"USDBYR": 17415,
"USDBZD": 1.994983,
"USDCAD": 1.315225,
"USDCDF": 929.999946,
"USDCHF": 0.99331,
"USDCLF": 0.024598,
"USDCLP": 692.094971,
"USDCNY": 6.33525,
"USDCOP": 2837.080078,
"USDCRC": 534.015015,
"USDCUC": 0.99991,
"USDCUP": 0.99978,
"USDCVE": 101.349503,
"USDCZK": 24.907012,
"USDDJF": 177.595001,
"USDDKK": 6.8657,
"USDDOP": 45.400002,
"USDDZD": 107.014999,
"USDEEK": 14.325002,
"USDEGP": 8.029699,
"USDERN": 15.279969,
"USDETB": 21.022499,
"USDEUR": 0.920471,
"USDFJD": 2.157498,
"USDFKP": 0.648499,
"USDGBP": 0.650132,
"USDGEL": 2.395014,
"USDZWL": 322.355011
}
}
I need to get value of "USDGBP" from that string. How can I do that? Preferably stored as double.
Rather than converting it into NSString try converting it in NSDictionary using
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
then you can retrieve value of USDGBP like
double usdgbp = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
double usdgbpValue = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
you can find the value in the string simply extracting a string between 2 string.
NSString *jsonStr = #"long json string";
NSRange str1 = [jsonStr rangeOfString:#"\"USDGBP\":"];
NSRange str2 = [jsonStr rangeOfString:#","];
NSRange strSub = NSMakeRange(str1.location + str1.length, str2.location - str1.location - str1.length);
NSString *valueForUSDGBP = [jsonStr substringWithRange:strSub];
You should use NSJSONSerialization
NSData *jsonData = your data ... ;
NSError *theError = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&theError];
if (theError) {
NSLog(#"%#", theError);
}
else {
double theValue = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
}
If you'd like to have much fun, use NSScanner to parse the string ;)
I am converting my json string to NSMutableDictionary by using below code,it's working fine,but if there is any unwanted white spaces are there then dictionary become null,i tested it with JSON lint, JSON parser, if i remove manually that white space that JSON string become valid, there is any method to remove that white spaces in JSON String.
NSMutableDictionary *responseDictionary;
NSData * data = (NSData *)responseObject;
NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
responseDictionary = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];
NSLog(#"the value in the dic is%#",responseDictionary);
Thanks In Advance
Ok, so if you're certain that you need to do it yourself, here is a way to do it:
NSString *theString = #" Hello this is a long string! ";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:#"SELF != ''"];
NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:#""]; // using empty string to concatenate the strings
P.S. This is a slightly modified version of this answer (the author deserves an upvote IMHO): https://stackoverflow.com/a/1427224/2799410
Try this:
NSString *newString= [jsonString stringByReplacingOccurrencesOfString:#" "
withString:#""];
Now the newString will not have any white spaces.