aotian16
aotian16

Reputation: 819

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

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")
}

Upvotes: 8

Views: 24733

Answers (4)

Sateesh Pasala
Sateesh Pasala

Reputation: 998

I got the same error. Turns out the mistake is in the request. The below syntax fixed the problem while adding parameters to the request.

request.setValue("Value", forHTTPHeaderField: "Key")

Upvotes: 0

Venu Gopal Tewari
Venu Gopal Tewari

Reputation: 5876

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.

Upvotes: 4

Krutarth Patel
Krutarth Patel

Reputation: 3455

Please check Response in Postman. i just solved by checking if json response is proper format or in html format

Upvotes: 0

Martin R
Martin R

Reputation: 540005

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)
// ...

Upvotes: 6

Related Questions