How to parse HTML JSON String - objective-c

I am troubling to parse JSON from Html String, Please suggest me better way to parse.
<html><head></head><body>{"data":{"type":"success","message":"Thanks for order with XYZ."}}</body></html>
This Html string response from stringByEvaluatingJavaScriptFromString API.
I want to parse "type" and "message" from above string. I am not getting expected result from rangeOfString API.
Thanks in advances.

Assuming you need this as a dictionary in Obj-C:
NSString * html = #"<html><head></head><body>{\"data\":{\"type\":\"success\",\"message\":\"Thanks for order with XYZ.\"}}</body></html>";
NSData * data = [html dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString * attributedString = [[NSAttributedString alloc] initWithHTML:data documentAttributes:nil];
NSData * jsonData = [attributedString.string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * result = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(#"Output %#",result);

Related

Unable to decode gzipped Base64 NSString

So I'm trying to decode a base64 encoded string but I'm not having any luck.. decodedString is always null! I've tried for hours and totally out of ideas. Even tried third party libraries.
Code:
NSString *input = #"H4sIAAAAAAAEALWSTW/TQBCG/0q15wTN7Je9voU2RFFUFCnuASGE9mMcTB0n9QcSQvx3xm6QWsSFAzev53l3Zp9dcb8+HFab9fZOFGJ/3Ny+bbvdrt+MX56ePp9OeDyKhSi3TJWr+z0zEtAtQS1RligLowowbxSAzqWdyA/7NUMP+7tVueb12FPXi5vi5uOP+XubuJoHkpjQOghBW5c5Dzpo0sZj8FYaztVtP6MSeHG+XIMKpJQEQQcgnSobrHVRxco6qY2WcgoOdHq4NkKzENV7fyKOrnx3brneXNeHoavjY+PbxD+jb6hNfg7BQlCqh7Kesb+eNkfjZM65R/o+zxUpwxAzTyoinyL5hLnPJBkbK6h8YPTSnb9SHGbcGcgQfJDBWY0qhop5ixoJdRYUMZ6oedf44zzO5G1ftxxEqbSx4uenufVvr/9vile3MJndPbeaxPaD715YskswS4WlxAKhgCnASv+wKPMSTYHuuf7NN3XyA92ex3bgTdU/mB8vU/Iw+GHsOfpa2MvrFEGBTSEjrPiRVImCT8T7qJSMs5VJbPMX5JgDcAQDAAA=";
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:input options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(#"Decode String Value: %#", decodedString);
The Base64 decoded output is not a string, it is binary data.
You are getting nil returned because it is not a UTF-8 string and arbitrary data is generally not valid UTF-8.
Decode using NSDataBase64DecodingIgnoreUnknownCharacters to avoid the decoder discarding non-Base-64 bytes.
NSData *decodedData = [[NSData alloc]initWithBase64EncodedString:input
options:NSDataBase64DecodingIgnoreUnknownCharacters];
Once you have decodedData, you can decompress the buffer with whatever function or library you decide on, then you can read the string. You may want to look at the answer here for an idea of how to decompress your data.
decodedData is not nil.
It's value is: <1f8b0800 ...
1f8b let me think it's a GZip.
Any hex data is not convertible as such into a String using UTF8 Encoding. UTF8 doesn't have value for each possible hex. There are non-valid combination, and so your final string is nil.
For instance, transform an UIImage into PNG HexData (using UIImagePNGRepresentation()) and try it to convert it into a NSString using NSUTF8StringEncoding. You'll see.
Using the code of https://github.com/nicklockwood/GZIP/ (first one I found):
NSData *unzippedData = [decodedData gunzippedData];
NSString *decodedString = [[NSString alloc] initWithData:unzippedData encoding:NSUTF8StringEncoding];
Output:
"MESSAGEID":"PgGCBnrKKsGuhqq_mm1gg","TIMESTAMP":"2019-03-12T12:53:05.3004826","TYPE":"UPDATE","users" : [{"userId":"8be21d1690bb46979a04b4e45a1ba625","insId":"20","operId":"30222e0b4b0e4df6b669c3cf69245422","itemUserId":15,"fName":"Aaron","lName":"Strickland","calendarId":0,"editTime":"2019-03-12T12:53:05.3815928","keyId":"ce71bc7ae3c145adad18a72e56cf0fab","projectId":"950710ab2b96413cbfd186141e147b3e","delFlag":0,"userPin":"123456"}],"keys" : [{"keyId":"ce71bc7ae3c145adad18a72e56cf0fab","projectId":"950710ab2b96413cbfd186141e147b3e","insId":"20","itemKeyId":15,"startTime":"2016-05-31T21:10:00","endTime":"2019-03-28T15:19:00","validateCount":13,"editTime":"2019-03-12T12:53:05.3815928","updateStatus":1,"delFlag":0,"calendarId":"b306db7e1f924fdebade3813dd596f5d"}]
Seems almost like JSON. I would have add "{" and "}" around it.
With a little of workaround:
NSMutableData *finalData = [[NSMutableData alloc] initWithData:[#"{" dataUsingEncoding:NSUTF8StringEncoding]];
[finalData appendData:unzippedData];
[finalData appendData:[#"}" dataUsingEncoding:NSUTF8StringEncoding]];
NSData *dictionary = [NSJSONSerialization JSONObjectWithData:finalData options:0 error:nil];
NSLog(#"dictionary: %#", dictionary);
It's up to you to know why the syntax is strange, but with that you a "usable" NSDictionary.

Parse string values

- i'm trying to parse this string values with Objective-C.
NSString * str= #"MyDataCallBack({
"one": "john",
"two": "mark",
"three": "hanna"
});";
i want to get the value content by name. Please consider this pseudo code:
NSString * data = parse("one");
then it will output the value of "one"
NSLog(#"The data value is %#\n", data); // The data value is john
but i don't have any idea how to achieve that. Please help me to achieve
that and show me how that is done with code.
You can directly use the NSJSONSerialization to achieve this:
NSString * str= #"MyDataCallBack({\"one\": \"john\", \"two\": \"mark\", \"three\": \"hanna\"});";
str = [str stringByReplacingOccurrencesOfString:#"MyDataCallBack(" withString:#""];
str = [str stringByReplacingOccurrencesOfString:#");" withString:#""];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *ec = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"%#",ec[#"one"]);
Hope this helps!

convert base64 decoded NSData to NSString

I'm trying to encode and decode base64 data. but while decoding the base64 data, it returns bunch of hex values, but i couldn't display or printout using NSlog to the original readable strings. The below code couldn't print anything, just empty.
Can anyone help ? thanks
>
>
NSString* msgEncoded = [[NSString alloc] initWithFormat:#"Q1NNKE1DTC9TTUEgUkNWL2FkbWluQHNldGVjcy5jb20gT1JHLyBUVkIvNDNkYzNlMzQwYWQ3Yzkp:"];
NSData* decoded = [[NSData alloc] initWithData:[self decodeBase64WithString:msgEncoded]];
NSString* plainString = [[NSString alloc]initWithData:decoded encoding:NSUTF8StringEncoding];
NSLog(#"\n Decoded string: %# \n", plainString );
There is a built in function in NSData
[data base64Encoding];
[data base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
If you are still having issues, try out this library: https://github.com/l4u/NSData-Base64
use it like so:
#import "NSData+Base64.h"
NSData *someData //load your data from a file, url or photo as needed
NSData *file = [NSData dataWithContentsOfFile:#"mytextfile.txt"];
NSData *photo = UIImageJPEGRepresentation(self.photo.image,1);
//encode it
NSString *base64string = [photo base64EncodedString];
NSString *base64file = [file base64EncodedString];
//decode it
NSData *back = [NSData dataFromBase64String:base64string];
Try Google's GTMStringEncoding class. You'll need GTMDefines.h too.
GTMStringEncoding *coder = [GTMStringEncoding rfc4648Base64StringEncoding];
NSString *encodedBase64 = [coder encodeString:#"Mary had a little lamb"];
// will contain the original text
NSString *decodedText = [coder decodeString:encodedBase64];
To encode NSData* to NSString* and back to NSData*, use the encode: + decode: methods instead of encodeString: + decodeString:.
As a bonus you get a lot of additional useful encodings, such as the url-safe variant of Base64.

Best way to parse a JSONP response

I am calling an API, which should return a JSON file. Here is the API link: http://sg.media-imdb.com/suggests/h/hello.json
The problem is: this JSON file has something wrapping the JSON response
imdb$hello(JSON)
So the best approch that I can see is to use a regex expression to extract only what I need. Something like: ~/\((.*)\)/.
However I would like to use the new JSON iOS5 API, which (as far as i know) only accepts NSData as input. So, I don't want to convert my response from NSData to NSString, parse that using regex, and put that in another NSData object.
Can anyone see a better/cleaner solution for that JSON parsing?
What you have isn't JSON, but JSONP. If you're not in JavaScript, I believe the correct way to handle is just as you say, preprocess and then parse.
NSError *jsonError = nil;
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSRange range = [jsonString rangeOfString:#"("];
range.location++;
range.length = [jsonString length] - range.location - 1;
jsonString = [jsonString substringWithRange:range ];
NSJSONSerialization *jsonResponse =
[NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
Why don't you just do something like this before parsing the JSON?
response = [response stringByReplacingOccurrencesOfString:#"imdb$hello" withString:#""];
How regular is this string. It will always be there?
// Remove #"imdb$hello(" and #")" that wraps the response string.
NSRange JSONRange = NSMakeRange(11, [responseString length] - 12);
NSString *JSONString = [responseString substringWithRange:JSONRange];
// Now you can parse as normal…
You will need to craft the method of peeling away the wrapper with your own level of certainty.

Pulling Data From JSON

I have a simple JSON string that looks like
(
{
ID = 1;
response = Yes;
}
)
And my NSDictionary is not pulling the objectForKey. The jsonArray is displaying correctly. My code:
hostStr = [[hostStr stringByAppendingString:post] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *hostURL = [NSURL URLWithString:hostStr];
NSString *jsonString = [[NSString alloc] initWithContentsOfURL:hostURL];
self.jsonArray = [jsonString JSONValue];
[jsonString release];
NSLog(#"%#", jsonArray);
NSDictionary *infoDictionary = [self.jsonArray objectForKey:#"ID"];
NSLog(infoDictionary);
This is probably the case since you have completely invalid JSON (test it out at http://jsonlint.com/). Because you are missing the quotation marks in your JSON the elements won't match the id ID. All object names/keys need to be in quotation marks.
You're lucky that your framework interprets your invalid JSON (somehow) correctly so that you actually get an array or a dictionary. Because of this the result of NSLog will be correct.
Rewrite your JSON like this to get it working:
{
"ID": 1,
"response": "YES"
}
(Also be sure that jsonArray is a NSDictionary)