简体   繁体   中英

How to convert dynamic NSString into JSON format in iOS?

please help me anyone i am trying to convert NSString into JSON for taking specific data from that string. This was my string and i try to convert from NSString into JSON. That string was dynamically fetch into that jsonString that was i paste in that string below.

NSString *jsonString = @"{status=success&unmappedstatus=captured&instrument_type=iOS&}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

the result will be displayed as null that i displays in NSLog and even in UIalert view

NSLog(@"-->>JSON_data: %@",json);

please help me anyone for this..

You should store your string as

    NSString *jsonString = @"{\"status\":\"success&amp\",\"unmappedstatus\":\"captured&amp\",\"instrument_type\":\"iOS&amp\"}";
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

Hope this will help you

It returns nil if it failed to parse. Use something like the following to get the error description:

NSError *error;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error) {
   NSLog(@"%@", error.localizedDescription);
}

The string what you are trying to convert into NSData and than back to JSON is not a valid JSON string.

Therefore you get null JSON data. This is what your string should look like:

{
"status":"success&amp",
"unmappedstatus" : "captured&amp" , 
"instrument_type" : "iOS&amp"
} 

You can validate a string as JSON under this link: http://www.jsoneditoronline.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM