Error in json parsing while converting response into NSDictionary - iphone

AM getting below error while converting json response into NSdictionary in json parsing...
ERROR:-JSONValue failed. Error trace is: (
Error Domain=org.brautaset.JSON.ErrorDomain Code=3 UserInfo=0x4d38270 "Unrecognised leading character"
)
any suggestion...

You most likely have the same issue as me... The returning data is in JSONP format instead of pure JSON. In other words you will be dealing with something like
functionCall({"Name": "Foo", "Id" : 1234, "Rank": 7});
instead of just
{"Name": "Foo", "Id" : 1234, "Rank": 7}
More info here
You'll need to strip the function and parentheses from the string before parsing it through the JSON Framework. You can do that with the following Regular Expression (spaced out to make it easier to see):
\w+ \s? \( ( \{ .* \} ) \}
And the script to write this is:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\\w+\\s?\\((\\{.*\\})\\)"
options:NSRegularExpressionCaseInsensitive
error:&error];
[regex replaceMatchesInString:resultString
options:0
range:NSMakeRange(0, [resultString length])
withTemplate:#"$1"];
NSLog(#"resultString = %#", resultString);
NSLog(#"converted = %#", [resultString JSONValue]);
where resultString is the response from the url request... It has to be stored as an NSMutableString in order for the regex to update it.

actually am not creating the json object by using api am retrieving it..
now i found the reason for that error. am not giving valid json object to covert into nsdictionary...So for getting valid json object we have to produce valid url to retrieve json object.
thanks for your suggestion...

Related

how to remove \ from a word \"hello\" in objective c?

From webservice i get the data as json but the problem is the json comes with all " with a \ ie "all" comes as \"all\"
How to make this a valid json and then a dictionary?
{
GetDataResult = "[{\"www\":{\"0\":{\"ID\":\"10233\",\"Queue\":\"COMPLETED\",\"EstCommName\":\"\U062e\U0631\U0645 \U0644\U0644\U0627\U0644\U0648\U0645\U0646\U064a\U0648\U0645 \U0648\U0627\U0644\U0632\U062c\U0627\U062c\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"},\"1\":{\"ID\":\"10304\",\"Queue\":\"COMPLETED\",\"EstCommName\":\"\U0627\U062d\U0645\U062f \U0627\U0644\U0643\U0646\U062f\U064a \U0644\U0644\U0627\U0644\U0645\U0648\U0646\U064a\U0648\U0645 \U0648\U0627\U0644\U0632\U062c\U0627\U062c\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"},\"2\":{\"ID\":\"10667\",\"Queue\":\"FRESH\",\"EstCommName\":\"\U0645\U0646\U062c\U0631\U0629 \U0627\U0644\U062e\U0632\U0646\U0629\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"},\"3\":{\"ID\":\"10777\",\"Queue\":\"FRESH\",\"EstCommName\":\"\U0645\U0624\U0633\U0633\U0647 \U062c\U0647\U0627\U0645 \U0644\U0627\U0639\U0645\U0627\U0644 \U0627\U0644\U0633\U064a\U0631\U0627\U0645\U064a\U0643\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"}}},{\"asd\":{}},{\"ssd\":{}}]";
In other words
TLDR
how to remove \ from a word \"hello\".? ie output needed is "hello".
What i tried
NSLog(#"%#",[[op objectForKey:#"GetSampleDataResult"] stringByReplacingOccurrencesOfString:#"\"" withString:#""]);
I have not tried this but something like this can work for you.
Sample Code :
NSString *yourString = [yourJSON objectForKey:#"GetDataResult"];
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *www = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"www :: %#",www);
I tried like this below:--
NSString *word= #"'\'hello'\'";
NSArray *arr=[word componentsSeparatedByString:#"'\'"];
for (NSString *str in arr)
{
if ([str length] >0)
{
NSLog(#"%#",str);
}
}
from the top of my head, to replace \" you need to specify it as \\\"
reason being that \ itself is used as an escape character and thus you need to escape:
\ with \\
" with \"
but the quotes are needed so you need to rid yourself of the \
so this:
NSLog(#"%#",[[op objectForKey:#"GetSampleDataResult"]
stringByReplacingOccurrencesOfString:#"\\"
withString:#""]);
but as mentioned, NSJSONSerialization is the best way to go about this
[string stringByReplacingOccurrencesOfString:#"\\\"" withString:#"\""];
Be careful with quotation marks and backslashes.
Result of \\\" will be \", exactly what you need to find.
Result of \" will be ", exactly what you need to replace.
Edit: This is answer to “How to remove \ from a word \"hello\"?”, not a solution to the problem.

regex to detect a pattern in a JSON string

I have a string like this
"Settings" : { "UserId" : 3, "UserToken" : "4578965235874158", "SecurityCode" : "111", "Password" : "12345", "UserPhone" : "555-555-1531", "drop" : -1, "UserLastName" : "Smith" }
I need a regular expression pattern to find the value of the "UserToken"( in this example 4578965235874158)
Sorry if this is a "Give me code" question, but I never worked with regular expressions and I do not have much time to learn and try to do it myself.
Thanks for help.
Additional notes:
I will use it in objective-C for an iPhone application. I don't know if that affect anything but just in case.
EDIT'
The pattern is: the key is always "UserToken" followed by a space then by a : then another space after that comes the value inside double Quotes ". I would like to get this value.
Since it's a json format you don't really need to parse it with regex, but if you need to, this can be a solution:
(?<="UserToken"\s:\s")\d+
I would have converted it and access all information I need like:
NSString *str = #"\"Settings\" : { \"UserId\" : 3, \"UserToken\" : \"4578965235874158\", \"SecurityCode\" : \"111\", \"Password\" : \"12345\", \"UserPhone\" : \"555-555-1531\", \"drop\" : -1, \"UserLastName\" : \"Smith\" }";
//NSDictionary *jsonDict = [str JSONValue];
NSError *error;
NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
than all information are stored on the results NSDictionary, just have to do something like: [results valueForKey:(NSString *)] or [results objectForKey::(NSString *)]

How to extarct string between two square bracket Objective C

I have string like this:
jsonArray:
{
d = "[{\"Training_Code\":\"1234 \",\"Training_Duration\":\"2hrs \",\"Training_Startdate\":\"14/02/2013 15:00:00\",\"Training_Enddate\":\"14/02/2013 17:00:00\",\"Trainer_ID\":1,\"Training_Location\":\"B-Wing Training room-4\",\"Comments\":\"C# training\",\"Keyword\":\"C#1234\",\"NumberofDays\":1},{\"Training_Code\":\"4321 \",\"Training_Duration\":\"16 \",\"Training_Startdate\":\"17/02/2013 10:30:00\",\"Training_Enddate\":\"17/02/2013 17:30:00\",\"Trainer_ID\":2,\"Training_Location\":\"A-Wing Training Room-6\",\"Comments\":\"Objective-C\",\"Keyword\":\"Obj-C4321\",\"NumberofDays\":2}]";
}
I want to get the data between two square bracket(including square bracket) and then remove all the "\" to get my final string like this:
[
{
"Training_Code": "1234",
"Training_Duration": "2hrs",
"Training_Startdate": "14/02/201315: 00: 00",
"Training_Enddate": "14/02/201317: 00: 00",
"Trainer_ID": 1,
"Training_Location": "B-WingTrainingroom-4",
"Comments": "C#training",
"Keyword": "C#1234",
"NumberofDays": 1
},
{
"Training_Code": "4321",
"Training_Duration": "16",
"Training_Startdate": "17/02/201310: 30: 00",
"Training_Enddate": "17/02/201317: 30: 00",
"Trainer_ID": 2,
"Training_Location": "A-WingTrainingRoom-6",
"Comments": "Objective-C",
"Keyword": "Obj-C4321",
"NumberofDays": 2
}
]
How can I do this in objective-c? thanks.
Try using JSONKit(ref) or NSJSONSerialization (ref), they will give either an NSArray or NSDictionary, depending on the structure of the JSON string.
UPDATE:
d looks like a well formed JSON string, but where is it coming from? Is it a char[] (as mentioned in the coments above), NSString, or console output?
It looks from here that your first code listing is what gets printed to the console. Printing JSON strings to the console will usually print the escape characters (\). In your other post, you are assuming every response can be parsed into an array. It would be safer to store the returned object into an id first, then check its class:
id rawData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError
if ( jsonParsingError != nil ) {
// investigate the parsing error
}
else if ( [rawData isKindOfClass[NSDictionary class]] ) {
NSDictionary *dict = rawData;
// process dictionary
}
else if ( [rawData isKindOfClass[NSArray class]] ) {
NSArray *array = rawData;
// process array
}
else {
// some thing went completely wrong
}
You also do not indicate that you are checking any possible errors. Inspecting jsonParsingError will likely give clues as to what is going on.
Use nsstring method dataUsingEncoding to get a nsdata instance.
Use NSJSONSerialization
The string you wanted is same as you provided.
Since d is a string:
To remove "\" , you could this:
NSString *newString = [myString stringByReplacingOccurrencesOfString:#"\" withString:#""];
Since the square brackets are at the front and the end, maybe you could do this:
[newString removeObjectAtIndex:0];
[newString removeObjectAtIndex:[newString count]-1];
first step is to get that string according to your situation and replace myString with your string.
Only if the source string contains one [ and ] each, then...
Use componentsSeparatedByString to split the source string with [.
Use componentsSeparatedByString to split the result (objectAtIndex:0) above with ].

regular expression to match " but not \"

How can I construct a regular expression which matches an literal " but only if it is not preceded by the escape slash namely \
I have a NSMutableString str which prints the following on NSLog. The String is received from a server online.
"Hi, check out \"this book \". Its cool"
I want to change it such that it prints the following on NSLog.
Hi, check out "this book ". Its cool
I was originally using replaceOccurencesOfString ""\" with "". But then it will do the following:
Hi, check out \this book \. Its cool
So, I concluded I need the above regular expression to match only " but not \" and then replace only those double quotes.
thanks
mbh
[^\\]\"
[^m] means does not match m
Not sure how this might translate to whatever is supported in the iOS apis, but, if they support anchoring (which I think all regex engines should), you're describing something like
(^|[^\])"
That is, match :
either the beginning of the string ^ or any character that's not
\ followed by:
the " character
If you want to do any sort of replacement, you'll have to grab the first (and only) group in the regex (that is the parenthetically grouped part of the expression) and use it in the replacement. Often this value labeled as $1 or \1 or something like that in your replacement string.
If the regex engine is PCRE based, of course you could put the grouped expression in a lookbehind so you wouldn't need to capture and save the capture in the replacement.
Not sure about regex, a simpler solution is,
NSString *str = #"\"Hi, check out \\\"this book \\\". Its cool\"";
NSLog(#"string before modification = %#", str);
str = [str stringByReplacingOccurrencesOfString:#"\\\"" withString:#"#$%$#"];
str = [str stringByReplacingOccurrencesOfString:#"\"" withString:#""];
str = [str stringByReplacingOccurrencesOfString:#"#$%$#" withString:#"\\\""];//assuming that the chances of having '#$%$#' in your string is zero, or else use more complicated word
NSLog(#"string after modification = %#", str);
Output:
string before modification = "Hi, check out \"this book \". Its cool"
string after modification = Hi, check out \"this book \". Its cool
Regex: [^\"].*[^\"]. which gives, Hi, check out \"this book \". Its cool
It looks like it's a JSON string? Perhaps created using json_encode() in PHP on the server? You should use the proper JSON parser in iOS. Don't use regex as you will run into bugs.
// fetch the data, eg this might return "Hi, check out \"this book \". Its cool"
NSData *data = [NSData dataWithContentsOfURL:#"http://example.com/foobar/"];
// decode the JSON string
NSError *error;
NSString *responseString = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
// check if it worked or not
if (!responseString || ![responseString isKindOfClass:[NSString class]]) {
NSLog(#"failed to decode server response. error: %#", error);
return;
}
// print it out
NSLog(#"decoded response: %#", responseString);
The output will be:
Hi, check out "this book ". Its cool
Note: the JSON decoding API accepts an NSData object, not an NSString object. I'm assuming you also have a data object and are converting it to a string at some point... but if you're not, you can convert NSString to NSData using:
NSString *responseString = [NSJSONSerialization JSONObjectWithData:[myString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
More details about JSON can be found at:
http://www.json.org
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

NSString: EOL and rangeOfString issues

Could someone please tell me if I am missing something here... I am trying to parse individual JSON objects out of a data stream. The data stream is buffered in a regular NSString, and the individual JSON objects are delineated by a EOL marker.
if([dataBuffer rangeOfString:#"\n"].location != NSNotFound) {
NSString *tmp = [dataBuffer stringByReplacingOccurrencesOfString:#"\n" withString:#"NEWLINE"];
NSLog(#"%#", tmp);
}
The code above outputs "...}NEWLINE{..." as expected. But if I change the #"\n" in the if-statement above to #"}\n", I get nothing.
Why don't you use - (NSArray *)componentsSeparatedByString:(NSString *)separator? You can give it a separator of #"\n" and the result will be a convenient array of strings representing your individual JSON strings which you can then iterate over.
if([dataBuffer rangeOfString:#"\n"].location != NSNotFound) {
NSArray* JSONstrings = [dataBuffer componentsSeparatedByString:#"\n"];
for(NSString* oneString in JSONstrings)
{
// here's where you process individual JSON strings
}
}
If you do mess with the terminating '}' you could make the JSON data invalid. Just break it up and pass it to the JSON library. There could easily be a trailing space after the '}' that is causing the problem you are observing.