NSData to NSString with JSON response
If you convert the JSON data
{ "result" : "\u8aaa" }
to a NSDictionary
(e.g. using NSJSONSerialization
) and print the dictionary
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(@"%@", jsonDict);
then you will get the output
{
result = "\U8aaa";
}
The reason is that the description
method of NSDictionary
uses "\Unnnn" escape sequences
for all non-ASCII characters. But that is only for display in the console, the dictionary is correct!
If you print the value of the key
NSLog(@"%@", [jsonDict objectForKey:@"result"]);
then you will get the expected output
說
How to NSLog NSData JSON response in JSON format?
• What's wrong:jsonData
(as you gave) IS NOT a hexData representing a JSON.
• Quick hack (not viable solution!) to get your JSON to use in your site CodeBeautify:
NSDictionary *dictFromData = [NSKeyedUnarchiver unarchiveObjectWithData:jsonData];
NSData *realJSONData = [NSJSONSerialization dataWithJSONObject:dictFromData options:0 error:nil];
NSString *strFINAL = [[NSString alloc] initWithData:realJSONData encoding:NSUTF8StringEncoding];
NSLog(@"StrFINAL: %@", strFINAL);
Note: Yeah, I bypassed the error
parameters, and we shouldn't. With
instead of
NSJSONWritingPrettyPrinted0
in options:
parameter, you have a result almost similar to the one of CodeBeautify.
• How did I get there:
Firt, I copy/paste your bump string of NSData
with this answer.
That way, I got jsonData
as you got.
Then, I tried simply what it should be given your informations:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&errorJSON];
Which didn't work giving the error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be
completed. (Cocoa error 3840.)" (Invalid value around character 0.)
UserInfo=0x17598540 {NSDebugDescription=Invalid value around character
0.}
But with NSDictionary *dictWithData = [NSKeyedUnarchiver unarchiveObjectWithData:jsonData];
, I managed to get the real NSDictionary
. But NSKeyedArchiver
/NSKeyedUnarchiver
are doing something "equivalent" to NSJSONSerialization
: it serializes, transforming a NSObject
into NSData
(and vice-versa). But more powerful: for any kind of object that are NSCoding
compliant. Here, since it's originally from a JSON (only NSString
, NSNumber
, NSArray
and NSDictionary
objects, and not a custom one), it's working without any more code.
Did you for instance tried to save it into NSUserDefaults
and it's not a .plist either (that was also one on my tries, I saved jsonData
into memory, and used dictionaryWithContentsOfFile:
giving me weird answer, but a important one in the bump of it: ""$class" = "{value = 23}";" which lead me to NSKeyArchiver
/NSKeyUnarchiver
). I don't know what you did exactly.
• Conclusion:
So clearly, somewhere, you mixed stuff found on the web. You need to rework that. You can't let it like this. There is issue in your code elsewhere. Where did you get jsonData
from? What did you do with it?
Convert NSData from NSURLSession to JSON
Your main issue:
If you read the error parameter of +JSONObjectWithData:options:error:
, it will tell you this:
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start
with array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or
object and option to allow fragments not set.}
As stated, your answer looks like this: aStringKey = realAndValidJSONSurroundedByCurvyBrackets
, which is not a valid JSON.
After discussion in chat, you have contact with the server side, and it should be their responsibility to give proper JSON. Until they fix it, in order to keep working, you can do:
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
str = [str stringByReplacingCharactersInRange:NSMakeRange(0, [@"aStringKey = " length] ) withString:@""];
NSError *jsonError = nil;
NSDictionary *jsonFinal = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&jsonError];
if (jsonError)
{
NSLog(@"Error: %@", jsonError);
}
But remember, that's a "quick hack/fix" and shouldn't be left in final version and remove as soon as possible.
You tried:
NSError *err = nil;
@try
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}
@catch (NSException *exception)
{
NSLog( @"Exception caught %@",exception);
}
The @try{}@catch(NSException *exception)
shouldn't work since +JSONObjectWithData:options:error:
shouldn't throw a NSException
in your case, so in theory, there is nothing to catch, and but it may still not work (since there is a NSError
).
Of course, since data
parameter should be non null, if it's nil
, you'll get a NSException
(which would log Exception caught data parameter is nil
), but that's another issue and doesn't assure you that the parsing went wrong (because of invalid JSON like in our case) if there is no exception.
NSJSONSerialization from NSString
First you will need to convert your NSString
to NSData
by doing the following
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
then simply use the JSONObjectWithData
method to convert it to JSON
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
convert JSONresponse to NSDATA or NSDICTIONARY in swift4
You are already using Alamofire as your network requester, So it is not necessary to convert the response object to JSON object or Data object. The library itself will provide to parsed JSON object. So check the below sample code to check the JSON object.
let urlString = "https://......"
let securityToken: String = "Basic YWFnZTQxNDAxMjgwODYyNDk3NWFiYWNhZjlhNjZjMDRlMWY6ODYyYTk0NTFhYjliNGY1M2EwZWJiOWI2ZWQ1ZjYwOGM="
var headers: HTTPHeaders = [:]
headers["Authorization"] = securityToken
let parameters: Parameters = ["city": 100, "minutesBehind" : 60, "miutesAhead" :0]
Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
if let jsonObject = response.result.value{
print("response.result.value \(String(describing: jsonObject))")
}
if let jsonObject = response.value{
print("response.value \(String(describing: jsonObject))")
}
}
Create JSON format using NSString as a key and values
Here is your answer :
NSString *strFName = @"XYZ";
NSString *strLName = @"ABC";
NSInteger number = 15;
NSString *strKeyFN = @"first_name";
NSString *strKeyLN = @"last_name";
NSString *numValue = @"Number";
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:strFName forKey:strKeyFN];
[dic setObject:strLName forKey:strKeyLN];
[dic setObject:[NSNumber numberWithInt:number] forKey:numValue];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dic] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JSON %@",jsonString);
How to parse the data into Json Format in ios?
If you got you response in json string then try like below,
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
here responseString
is final output json string that you have posted in question.
Then fetch data from json dictionary
.
If this scenario will not work then take a look at NSXMLParser, you can refer Appcoda's tutorial.
Parsing NSData to Json failed in my swift app
I'm certain that it isn't an array, its a dictionary. Parse to Json like this:
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as! NSDictionary
And to get definition key, do this
res.valueForKeyPath("results.definition")
Related Topics
How to Find Serial Number, Imei Number Using iOS Sdk
Uisearchbar's Cancel and Clear Buttons Not Working in iOS 7
Are Extensions Bad for Performance in Swift
How to Add Text, Shape and Signature in Photo Markup with Pencil Kit
Nsstrikethroughstyleattributename , How to Strike Out the String in iOS 10.3
Swift Put Multiple Iboutlets in an Array
Itms-90809: Deprecated API Usage - Existing App That Use Uiwebview Are No Longer Accepted
Libz.Dylib Versus Libz.1.2.3.Dylib Versus Libz.1.2.5.Dylib
Is Iboutletcollection Guaranteed to Be of Correct Order
Flutter: Disable Swipe to Navigate Back in iOS and Android
Contact Address Book Crash on iOS 10 Beta
Clip Image to Square in Swiftui
Could an iOS Application Read/Access Sms Text
Programmatically Highlight Uibarbuttonitem
Firebase - How to Get the Key Value in Observeeventtype = Value