Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSJSONSerialization error. Code=3840 "Invalid value around character 0

Tags:

swift

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")
}
like image 307
aotian16 Avatar asked Nov 04 '15 10:11

aotian16


2 Answers

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)
// ...
like image 176
Martin R Avatar answered Nov 20 '22 16:11

Martin R


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.

like image 33
Venu Gopal Tewari Avatar answered Nov 20 '22 15:11

Venu Gopal Tewari