How to convert UTF8String to JSON based NSDictionary? - ios

I am getting one of my web-service response in JSON. Here is the UTF8String base responseString:
"{\"ApplicationId\":1,\"CurrentPosition\":0,\"EndOfFile\":false,\"Media\":{\"Active\":true,\"Description\":\"This video demonstrates a quick overview of Bentley LEARN Server.\",\"LocationId\":1,\"MP4URL\":\"http:\\/\\/cdnllnw.bentley.com\\/s\\/LearnVideo\\/Welcome.mp4?s=1380034262&e=1380077462&h=c2641922fd862ffe5c5a05e94786359a\",\"MediaId\":5003235,\"MediaURL\":\"http:\\/\\/cdnllnw.bentley.com\\/s\\/LearnVideo\\/Welcome.mp4?s=1380034262&e=1380077462&h=c2641922fd862ffe5c5a05e94786359a\",\"StreamServer\":null,\"Title\":\"Welcome\",\"TransferStatus\":0,\"filesize\":9094429},\"MediaDuration\":0,\"SkippedCurrentPosition\":0,\"UserBP\":8011512,\"ViewedTime\":0}"
After formatting it looks like:
{
"ApplicationId":1,
"CurrentPosition":0,
"EndOfFile":false,
"Media":
{
"Active":true,
"Description":"This video demonstrates a quick overview of Bentley LEARN Server.",
"LocationId":1,
"MP4URL":"http:\/\/cdnllnw.bentley.com\/s\/LearnVideo\/Welcome.mp4?s=1380035311&e=1380078511&h=d8de8ade046266fb7324be90a575f978",
"MediaId":5003235,
"MediaURL":"http:\/\/cdnllnw.bentley.com\/s\/LearnVideo\/Welcome.mp4?s=1380035311&e=1380078511&h=d8de8ade046266fb7324be90a575f978",
"StreamServer":null,
"Title":"Welcome",
"TransferStatus":0,
"filesize":9094429
},
"MediaDuration":0,
"SkippedCurrentPosition":0,
"UserBP":8011512,
"ViewedTime":0
}
How can I convert this string into JSON object or NSDictionary object so that I can access all key-values easily.
I have tried this:
NSString *responseString = [NSString stringWithUTF8String:response.c_str()];
NSDictionary *JSONdict =
[NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
But it says JSONdict is nil and error description is:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0xd8bbd30 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
Please help

Adding NSJSONReadingAllowFragments as option should help according to error:
NSString* jsonString = #"{\"ApplicationId\":1,\"CurrentPosition\":0,\"EndOfFile\":false,\"Media\":{\"Active\":true,\"Description\":\"This video demonstrates a quick overview of Bentley LEARN Server.\",\"LocationId\":1,\"MP4URL\":\"http:\\/\\/cdnllnw.bentley.com\\/s\\/LearnVideo\\/Welcome.mp4?s=1380034262&e=1380077462&h=c2641922fd862ffe5c5a05e94786359a\",\"MediaId\":5003235,\"MediaURL\":\"http:\\/\\/cdnllnw.bentley.com\\/s\\/LearnVideo\\/Welcome.mp4?s=1380034262&e=1380077462&h=c2641922fd862ffe5c5a05e94786359a\",\"StreamServer\":null,\"Title\":\"Welcome\",\"TransferStatus\":0,\"filesize\":9094429},\"MediaDuration\":0,\"SkippedCurrentPosition\":0,\"UserBP\":8011512,\"ViewedTime\":0}";
NSError* error = nil;
NSDictionary *JSONdict =
[NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers | NSJSONReadingAllowFragments
error: &error];
But that means the NSString you pasted in your question contains extra characters which are not following JSON format. If you add more code from where you take this value (file, web) - I can help more to make it valid. Until then treat this answer as workaround :)
The properly formatted string should be:
{\"ApplicationId\":1,\"CurrentPosition\":0,\"EndOfFile\":false,\"Media\":{\"Active\":true,\"Description\":\"This video demonstrates a quick overview of Bentley LEARN Server.\",\"LocationId\":1,\"MP4URL\":\"http:\\/\\/cdnllnw.bentley.com\\/s\\/LearnVideo\\/Welcome.mp4?s=1380034262&e=1380077462&h=c2641922fd862ffe5c5a05e94786359a\",\"MediaId\":5003235,\"MediaURL\":\"http:\\/\\/cdnllnw.bentley.com\\/s\\/LearnVideo\\/Welcome.mp4?s=1380034262&e=1380077462&h=c2641922fd862ffe5c5a05e94786359a\",\"StreamServer\":null,\"Title\":\"Welcome\",\"TransferStatus\":0,\"filesize\":9094429},\"MediaDuration\":0,\"SkippedCurrentPosition\":0,\"UserBP\":8011512,\"ViewedTime\":0}
Without " at the beggining and at the end. Maybe that's the reason.
If you are loading this from web - make sure you don't have any JS included or extra headers and confirm that your web service responds with JSON format in headers.

I've try your NSString with the next piece of code (it's a starting point) to output the dictionary from "Media";
NSString *string = #"{\"ApplicationId\":1,\"CurrentPosition\":0,\"EndOfFile\":false,\"Media\":{\"Active\":true,\"Description\":\"This video demonstrates a quick overview of Bentley LEARN Server.\",\"LocationId\":1,\"MP4URL\":\"http:\\/\\/cdnllnw.bentley.com\\/s\\/LearnVideo\\/Welcome.mp4?s=1380034262&e=1380077462&h=c2641922fd862ffe5c5a05e94786359a\",\"MediaId\":5003235,\"MediaURL\":\"http:\\/\\/cdnllnw.bentley.com\\/s\\/LearnVideo\\/Welcome.mp4?s=1380034262&e=1380077462&h=c2641922fd862ffe5c5a05e94786359a\",\"StreamServer\":null,\"Title\":\"Welcome\",\"TransferStatus\":0,\"filesize\":9094429},\"MediaDuration\":0,\"SkippedCurrentPosition\":0,\"UserBP\":8011512,\"ViewedTime\":0}";
NSString *newString = [string stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[newString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"%#", [dictionary valueForKey:#"Media"]);
And the result is:
{
Active = 1;
Description = "This video demonstrates a quick overview of Bentley LEARN Server.";
LocationId = 1;
MP4URL = "http://cdnllnw.bentley.com/s/LearnVideo/Welcome.mp4?s=1380034262&e=1380077462&h=c2641922fd862ffe5c5a05e94786359a";
MediaId = 5003235;
MediaURL = "http://cdnllnw.bentley.com/s/LearnVideo/Welcome.mp4?s=1380034262&e=1380077462&h=c2641922fd862ffe5c5a05e94786359a";
StreamServer = "<null>";
Title = Welcome;
TransferStatus = 0;
filesize = 9094429;
}
Hope it will be useful for you.

Related

How to remove the backslash (“\”) in the json response ,Objective C?

How to remove backslash(/)?. Every parameter is coming with backslash.All values stored in dictionary
ex:getCategoryListReturn" :"[{\"categoryId\":734, \"categoryNm\":\"Projector Dealers\",\"categoryNmBl\":\"تجار العارض\/مسلاط\",\"prntCategoryId\":733},{\"categoryId\":735,\"categoryNm\":\"Computer Dealers\",\"categoryNmBl\":\"تجار الحاسب الآلي \",\"prntCategoryId\":733},{\"categoryId\":736,\"categoryNm\":\"Laptop Dealers\",\"categoryNmBl\":\"تجار الحاسب الآلي\",\"prntCategoryId\":733},{\"categoryId\":737,\"categoryNm\":\"Printer Dealers\",\"categoryNmBl\":\"الطباعة\",\"prntCategoryId\":733},{\"categoryId\":738,\"categoryNm\":\"Colour Printer Dealers\",\"categoryNmBl\":\"تجار الطباعة الملونة\",\"prntCategoryId\":733},{\"categoryId\":739,\"categoryNm\":\"Laser Printer Dealers\",\"categoryNmBl\":\"الطباعة بالليزر\",\"prntCategoryId\":733},{\"categoryId\":740,\"categoryNm\":\"All In One Printer Dealers\",\"categoryNmBl\":\"اعمال الطباعة \",\"prntCategoryId\":733},{\"categoryId\":741,\"categoryNm\":\"Colour Laser Printer Dealers\",\"categoryNmBl\":\"الطباعة الملونة\",\"prntCategoryId\":733},{\"categoryId\":}
Follow the below code to remove backslash(/n)
NSData *data1 = [[dictionary valueForKey:#"getCategoryListReturn"] dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:nil];

Converting JSON string into object

I am trying to convert a JSON string into an object in Objective C using the code:
NSString *jsonString = (NSString *) responseObject;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
The value of jsonString is
"[{\"Date\": \"12-01-2015\", \"Time\": \"7:00 am\", \"Title\":
\"First Car Service\", \"Details\": \"This was the first car
service ever done\"}]"
But the value of json is always nil. How do I convert the jsonString into a NSArray ?
My (third) bet: your json string isn't correct. If it contains the leading and trailing quotes strip them. Replaced the \" with ".
better: make the server or other json source send correct json.
From the error, it may be that your string is not formatted correctly, probably due to the quotes.
You should also make sure that after you have formatted the string, then you check the array has objects.
NSLog(#"JSON Details: %#", json[0][#"Details"]);

NSJSONSerialization JSONObjectWithData where data contains line break characters

Sample Code:
NSString *jsonObject = ...;
BOOL isValidJSONObject = [NSJSONSerialization isValidJSONObject:jsonObject];
id jsonResponse = [NSJSONSerialization JSONObjectWithData:parsedData
options:NSJSONReadingAllowFragments
error:&jsonError];
Issue:
If jsonObject contains string data with newline characters, then NSJSONSerialization fails to parse and return a valid jsonRespone object. It returns following error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unescaped control character around character 119.) UserInfo=0x10ba9fef0 {NSDebugDescription=Unescaped control character around character 119.}
Sample JSON String (with newline character):
{"Name" : "Lorum","Description" : "Sample:
Lorum ipsum","Quantity" : 1,"Type" : 1}
What's the best way to handle this situation? Newline/ line break character should be valid in this case.
YES, double backslash is needed. However slash is not need to write twice.
For example,
jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:#[#"line 0\nline1", #"http://twitter.com"] options:0 error:nil] encoding:NSUTF8StringEncoding];
when hover your cursor on jsonString, Xcode will tell you what it exactly want. If you write
jsonString = #"[\"http://twitter.com\"]",
you can get correct answer when using NSJSONSerialization to parse the string. Even you know the more suitable input is
jsonString = #"[\"http:\\/\\/twitter.com\"]".

How to process response from Instapaper API?

I make a request to the Instapaper API, and it's supposed to return JSON. It returns something close to JSON, but not completely, like follows:
2013-05-30 19:54:20.155 --[53078:c07] (
{
type = meta;
},
{
"subscription_is_active" = 1;
type = user;
"user_id" = --;
username = "--#gmail.com";
},
{
"bookmark_id" = 387838931;
description = "";
hash = YHwQuwhW;
"private_source" = "";
progress = 0;
"progress_timestamp" = 0;
starred = 0;
time = 1369954406;
title = "Adobe Finally Releases Kuler Color-Picking App for iPhone - Mac Rumors";
type = bookmark;
url = "http://www.macrumors.com/2013/05/30/adobe-finally-releases-kuler-color-picking-app-for-iphone/";
},
How do I then process this? Can I take it and turn it into an NSDictionary even though it doesn't seem to be valid JSON?
From Instapaper API Docs:
Instapaper strings are always encoded in UTF-8, and Instapaper expects all input to be in UTF-8.
Unless otherwise noted, output from every method is an array. The output array is returned as JSON by default.
You can specify a jsonp parameter with a callback function name, e.g. jsonp=myCallback, to use JSONP and wrap the output in a call to the specified function.
So there is no way you will get not valid JSON!
Try following code:
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL urlWithString:#"http://your-instapeper-API-link"] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id serializationJSON = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
And then you can log what is wrong or if result is what you expect:
NSLog(#"class of JSON input: %# \n and possible error: %#",[serializationJSON class],error);
Of course you should expect Array and no error.
EDIT ... based on coment code:
Based on docs you should get Array or Dictionary. Please add this core instead your line #23 (numer from here):
if([JSON isKindOfClass:[NSDictionary class]]) {
NSDictionary *jsonDictionary = JSON;
NSLog(#"%#",[jsonDictionary allKeys]);
} else {
NSLog(#"JSON object class: %#",[JSON class]);
}
and please show us output.
One more thing:
You get array from request. Great! This is a valid JSON. So you need to debug it. As i said it's a shame is not a unlimited acccess public API, so i can look into it. But now you have to debug your result. I see in your code that you are trying to access bookmarks. So i look into Bookmarks section in docs and this is some kind of list (NSArray). So if you don't know what result you want. You should print them into log (or set a breakpoint). Replace code from my earlier update with this simple log:
NSDictionary *resultDictionary;
if([JSON isKindOfClass:[NSArray class]]) {
NSArray *jsonArray = JSON;
NSLog(#"so json is an array with %i objects",[jsonArray count]);
for(id objectInsideArr in jsonArray) {
NSLog(#"object in array [class]: %# [value]: %#",[objectInsideArr class],objectInsideArr); //if here you find NSDictionary maybe is this dictionary you are looking for. I'm not sure what it is.
if([objectInsideArr isKindOfClass:[NSDictionary class]]) {
resultDictionary = [[NSDictionary alloc] initWithDictionary:objectInsideArr];
}
}
}
If it were me I would write a custom formatter to get it into JSON format and then use NSJSONSerialization once I know it is valid. What you posted is so far from valid there is no way it would work. I'm surprised they are returning it in that format, do they provide some kind of library for consuming their services?
If you want something even simpler, I can give you my CGIJSONObject library that will handle JSON using reflection - you just need to mirror the keys in APIs with your classes andit is good to go.

Parse double quotes and single quotes in Json Parsing

I am parsing a JSON url. I am getting \u00e2\u20ac\u0153 instead of single quotes and \u00e2\u20ac\u009d instead of double quotes. On my end i am doing NSUTF8StringEncoding but still not getting single and double quotes.
Here is the response in the web browser:
{"status":"1","data":[{"id":"1345","title_en":"","content_en":"Mom
said, \u00e2\u20ac\u0153I love this one.\u00e2\u20ac\u009d\n\nJake
said, \u00e2\u20ac\u0153I don\u00e2\u20ac\u2122t get
it.\u00e2\u20ac\u009d\n","image":"1396","pos":"2","video_type":"0","video":"0","video_alt":"","sound_type":"1","sound":"1123","sound_alt":"","author":"","type":"0","book_id":"148","user_id":"24","title":"The
Art
Museum","author_url":"maureen-d-1","book_url":"the-art-museum","video_filename":"","sound_filename":"atmuseum2.m4a"}]}
Is it possible to parse above response using NSUTF8StringEncoding or something else. Or i need to get it done from php side.
Do you use NSJSONSerialization? In my app i do this:
NSError* localError;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&localError];
In "data" variable i have response from server. I receiving UTF-encoded text from server too (like \u00e2\u20ac) but finally i get normal string. "jsonObjects" will contain data in native types:
if ([jsonObjects isKindOfClass:[NSDictionary class]])
{
NSNumber* age = [jsonObjects objectForKey:#"age"];
//...etc
}

Resources