NSJSONSerialization.JSONObjectWithData
error when using a string like "abc" but success using "123"
I do not know why.
error log
2015-11-04 17:42:02.997 SwiftJsonDemo[27196:2701028] Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
code
//var str = "123" // ok
var str = "abc" // error
let strData = str.dataUsingEncoding(NSUTF8StringEncoding)
if let d = strData {
let urlStr = String(data: d, encoding: NSUTF8StringEncoding)
do {
let json = try NSJSONSerialization.JSONObjectWithData(d, options: NSJSONReadingOptions.AllowFragments)
} catch let e {
print(e)
}
} else {
print("data error")
}
123
is a valid JSON number, so this can be read as JSON if the .AllowFragments
option is set. JSON strings must be enclosed in quotation marks:
(see http://www.json.org for the details):
"abc"
In a Swift string literal, these quotation marks are escaped with backslashes:
let str = "\"abc\"" // OK!
let strData = str.dataUsingEncoding(NSUTF8StringEncoding)
// ...
Check with following line of code if using swift:
let contentType = response.response?.allHeaderFields["Content-Type"] as? String
Content type will be not coming as: "application/json". It implies response from server is not a valid JSON string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With