NSJSONSerialization error. Code=3840 "Invalid value around character 0 - 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")
}

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.

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

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

Related

Clarifications on JSONDecoder when decoding a single value

I was trying to perform some tests on JSONDecoder and I've encountered a strange behavior. In particular, when I use the following code an error is thrown.
let data = "Sample String".data(using: .utf8)!
do {
let decoder = JSONDecoder()
let decoded = try decoder.decode(String.self, from: data)
print(decoded)
} catch {
print(error)
}
dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})))
On the contrary if I put a number as string and Int.self as the decoding type the value is printed correctly.
let data = "100".data(using: .utf8)!
do {
let decoder = JSONDecoder()
let decoded = try decoder.decode(Int.self, from: data)
print(decoded)
} catch {
print(error)
}
100
Any reason why this happens?
because some string is not valid json, but "some string" is.
you need quotes in your string:
let data = "\"Sample String\"".data(using: .utf8)!

Prepare String for URL cast in Swift

I have a text Area, the content of which will later be used to create a URL. How can I validate that the url - cast doesn't throw an error? Is there a function that can do that? For example remove all invalid Characters. I cast the String in the following way, but if the user inputs a newline the cast doesn't work:let url: URL = URL(string: urlPath)!
Use optional binding (https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html):
var str = "somescheme://somedata"
if let url = URL(string: str) {
// handle url
} else {
// handle error
}
If you want to strip whitespaces and new line characters, use:
str.trimmingCharacters(in: .whitespacesAndNewlines)

error when convert JSON to Dictionary Swift

can you help me,
I'm facing an issue if the JSON came with multilines like this
"{\"groupId\":\"58\",\"chat\":\"send 2lines\nsecondline\"}"
I'm taking the response from server and convert it with this function
let dataDic = self.convertToDictionary(text: (remoteMessage.appData["message"]! as AnyObject) as! String)
print(dataDic!)
and this is my function
func convertToDictionary(text: String) -> [String: AnyObject]? {
if let data = text.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
return json
} catch {
print(error.localizedDescription)
}
}
return nil
}
but the problem came if the code have multilines because it's put \n in the return and
it gives me
The data couldn’t be read because it isn’t in the correct format
Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control character around character 145." UserInfo={NSDebugDescription=Unescaped control character around character 145.}
You should put an extra "\" before "\n", before parsing your JSON. Try using "replacingOccurencesOf" function.
That way your JSON is formatted before parsing.

RSAUtils Decryption , Converting data to it's original value - Swift

i am trying to encrypt and decrypt a string using RSAUtils swift library, i am having a problem returning the decrypted text to it's original value . this is the code:
let PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJh+/sdLdlVVcM5V5/j/RbwM8SL++Sc3dMqMK1nP73XYKhvO63bxPkWwaY0kwcUU40+QducwjueVOzcPFvHf+fECAwEAAQ=="
let sampleText:String = "WHATS UP"
let encrypted:Data? = RSAUtils.encryptWithRSAPublicKey(sampleText.data(using: String.Encoding.utf8)!, pubkeyBase64: PUBLIC_KEY, keychainTag: "12345")!
let decrypted:Data? = RSAUtils.decryptWithRSAPublicKey(encrypted!, pubkeyBase64: PUBLIC_KEY, keychainTag: "12345")
let encryptedDataText = encrypted!.base64EncodedString(options: NSData.Base64EncodingOptions())
let decryptedDataText = decrypted!.base64EncodedString(options: NSData.Base64EncodingOptions())
I tried to convert the decrypted data to string using this code:
if let string = String(data: decrypted! , encoding: .utf16) {
print(string)
} else {
print("not a valid UTF-16 sequence")
}
But it prints "㺸ꉄ꤈꽹㲞㏯荘뼵鉉큅령嬰ꢤẲ毪쌶⏤ᱼ埡佒�ࡊᩏ⧚㨈؍੯屍" I also tried to decode the base64 value using :
let decodedData = Data(base64Encoded: decryptedDataText)!
let decodedString = String(data: decodedData, encoding: .utf8)!
print(decodedString)
It causes an error
Fatal error: Unexpectedly found nil while unwrapping an O
probably the text is not a valid base64 string.
How can i convert the decrypted data to it's original value.
Thanks.

Alamofire JSON response with strange characters in Swift

I'm using Alamofire 3.0 and swift 2 and get a strange response from the following request:
func requestURLwithHeadersAndParams(URLstr:String, connectionMethod: Alamofire.Method, header: [String : String], body:[String : AnyObject], completion: (reponse: String, statusCode: Int, error: String) -> Void) {
///Singleton Alamofire connection manager
let alamofireManager = Alamofire.Manager.sharedInstance
alamofireManager.request(connectionMethod, URLstr, parameters: body, encoding: ParameterEncoding.JSON, headers: header).responseJSON (){
response in
print("\nSuccess: \(response.result.isSuccess)")
switch response.result {
case .Success(let value):
print("Response Status code: \((response.response?.statusCode)!)\n")
print("\(value)")
completion(reponse: "\(value)" , statusCode: (response.response?.statusCode)! , error: "")
case .Failure(let error):
print("Error Code:\(error.code) - Description:\(error.localizedDescription)")
completion(reponse: "Error" , statusCode: (response.response?.statusCode)!, error: error.localizedDescription)
} } }
the value property contains:
"{\n \"auth_token\" = \"qcW-mQmyX8ototieJu7WK\";\n avatar = {\n standard = {\n url = \"<null>\";\n };\n url = \"<null>\";\n };\n birthdate = \"<null>\";\n \"created_at\" = \"2015-10-28T07:02:20.445Z\";\n email = \"elrope#abt.com\";\n \"first_name\" = El;\n id = 12;\n \"last_name\" = Perro;\n role = user;\n \"shooter_type\" = \"\";\n \"updated_at\" = \"2015-10-28T07:42:37.860Z\";\n}"
any idea how can I get rid of all the escape characters ('\' and '\n') since the JSON serialization using SwiftyJSON in the method calling this method can't recognize the string as a json string and fails when I do let json = JSON(reponse) with error:
Error Domain=SwiftyJSONErrorDomain Code=901 "Dictionary["auth_token"]
failure, It is not an dictionary" UserInfo=0x6030002d7c00
{NSLocalizedDescription=Dictionary["auth_token"] failure, It is not an
dictionary})
I found your JSON invalid itself.
e.g. avatar, standard are not strings, where are the quotes?
I belevie using , and : is better practice than using ; and =
I tested on SwiftyJSON and after above changes everything works fine. So maybe the issue is on your backend. Try to validate raw JSON using web browser.
Your JSON is invalid.
Actually, your value string is nothing else than the .description output of an NSDictionary!
Demonstration in a Playground:
Needless to say that this isn't JSON... so of course it fails when you try to give this to SwiftyJSON.
So, either you were confused somewhere and you're using your dictionary's description instead of its actual content...
...or this error comes from the server.