Parse string values - objective-c

- 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!

Related

How to parse HTML JSON String

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);

Incorrect result from NSJSON Serialization

I have got a very strange issue when I trying to deserialize my json string, the code is this:
NSString *testString = #"{\"cash\": 99946.222300000000}";
// NSString *testString = #"{\"cash\": \"99946.222300000000\"}"; //It's correct if I use this one
NSData *jsonData = [testString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Convertion result is %#",error?#"false":#"true");
NSLog(#"Result data is\n %#",jsonObject);
And the result is :
2017-08-30 18:04:36.430 DAE[45557:2989692] Conversion result is true
2017-08-30 18:04:36.430 DAE[45557:2989692] Result data is
{
cash = "99946.22229999999";
}
So can anybody tell me if I did anything wrong? and how to solve it?
Really appreciate for any help.
First of all, it’s not wrong, it’s correct.
So, why you got the incorrect result?
First, The json value will be converted to a NSNumber object by NSJSONSerialization;
Then, the -description method of NSDictionary generate the result by stringValue method.
You should resolve the json value by this way to get the correct string:
[NSString stringWithFormat:%lf, [jValue doubleValue]]
But you should pay attention to the length of the value, the max length of double is 16, so if you get a number over than it, you will never get the correct result.
Tell your backend guy that they should convert all the numbers to string before they give them out, because it’s really hard to resolve them correctly if it’s big enough.
use it as Your commented string
NSString *testString = #"{\"cash\": \"99946.222300000000\"}";
NSData *jsonData = [testString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Convertion result is %#",error?#"false":#"true");
NSLog(#"Result data is\n %#",jsonObject);

How to convert NSString object into Array in Objective-C?

I have below string:
{"list": {"array":[{"current_rate":20.0,"id":1, "name": "abc"},
{"current_rate":20.0,"id":2, "name": "xyz"}]}}
I want to convert above string into array like
[current_rate: 20.0, id: 1, name: abc]
I used componentSeperatedByString:#":".
But it gives problem when name field contain ":" string.
Is there any way to convert above string into array.
The string you have seems valid JSON. You may want to parse it:
NSData *data = [theString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
Then you can get the object using the objectForKey: and objectAtIndex: methods on the appropriate classes.

Converting two double values to String and then making a string using the new strings

I am trying to convert two values to string and then make a new string containing the ones i made earlier so my service can accept them.
NSString *string1 = [ NSString stringWithFormat:#"%f", locationController.dblLatitude];
NSString *string2 = [ NSString stringWithFormat:#"%f", locationController.dblLongitude];
body = [[NSString stringWithFormat:#"geoX#%##geoY#%#", string1, string2] dataUsingEncoding:NSUTF8StringEncoding];
This is the code i am using atm. The problem is that both string1 and string2 appear to be ok but the string named body appears to not working.. :< Any help ?
body is not an NSString instance here, but NSData (because you're using `dataUsingEncoding:".
If you want to see concatenation of stings in system log you should write something like that:
NSString* bodyString = [NSString stringWithFormat:#"geoX#%##geoY#%#", string1, string2];
NSData* bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
and then you can NSLog(#"Body: %#", bodyString); to see it's contents and then use bodyData for making http request.
body is not an NSString; it is an NSData because of your call to dataUsingEncoding.
I believe this is happening because you are just logging the raw data. Try creating a string from the data and then logging it like this:
body = [[NSString stringWithFormat:#"geoX#%##geoY#%#", string1, string2] dataUsingEncoding:NSUTF8StringEncoding];
NSString *string = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);

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)