SWIFT - JSON error: The data couldn’t be read because it isn’t in the correct format - ios

How to correct this error: JSON error: The data couldn’t be read because it isn’t in the correct format?
struct LanguageText: Decodable {
let id_language: Int
let language_text: String
}
func textLoad() {
let switchcase = "loginWords"
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "switchcase=\(switchcase)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
return // check for fundamental networking error
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print("JSON error: \(error.localizedDescription)")
}
}.resume()
}
This is the JSON format:
[{"id_language":"15","language_text":"Female"},
{"id_language":"16","language_text":"Male"},
{"id_language":"17","language_text":"Other"},
{"id_language":"1000","language_text":"Hello there!"}]
Thanks!

You are trying to put id_language into a Int-Value, but in your JSON id_language is String.
Change id_language to String
struct LanguageText: Decodable {
let id_language: String
let language_text: String
}
Or you have to edit your JSON-File
[{"id_language":15,"language_text":"Female"},
{"id_language":16,"language_text":"Male"},
{"id_language":17,"language_text":"Other"},
{"id_language":1000,"language_text":"Hello there!"}]
For parsing JSON I can recommend this site

In your model you could do something like this:
struct LanguageText: Decodable {
let languageId: String
let languageText: String
enum CodingKeys: String, CodingKey {
case languageId = "id_language"
case languageText = "language_text"
}
}
In your do catch do the data parse:
do {
let result = try JSONDecoder().decode([LanguageText].self, from: data)
} catch {
print("JSON error: \(error.localizedDescription)")
}

Use this to get array from row data.
let dataArray = getArrayFromJsonString(rowData: data)
func getArrayFromJsonString(arrayString:String)-> [[String : Any]] {
do {
return try JSONSerialization.jsonObject(with:
arrayString.data(using:
String.Encoding.utf8, allowLossyConversion: false)!,
options:
JSONSerialization.ReadingOptions.allowFragments) as! [[String :
Any]]
} catch let error {
print("Error: \(error)")
return []
}
}

Related

how to parse JSON array inside object in swift4

I'M using tableview to parsing JSON data. the parse data in tableview in successful parsed on my tableView but the problem is users click the tableview cell to pass to details ViewController.But the problem is i can't parse JSON in details ViewController in
here is my JSON looks
[
{
"id": "263",
"userId": "2692"
}
]
here is my code
guard let url = URL(string: URL API) else { return }
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(AccessToken!)", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [string: anyobject]
print(json)
label.text = json["id"] as? string
}catch {
}
}.resume()
Please try this codes
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [[String: String]] {
for data in json {
label.text = data["id"] as? String
}
}
} catch { print(error) }
Parse json in swift4 using Codable protocol.
declare your model like this:
struct Model: Codable {
let id: Double
let userId: Double
enum CodingKeys : String, CodingKey {
case id = "id"
case userId = "userId"
}
}
then, after getting data, use this:
do {
let arrayValue = try JSONDecoder().decode([Model], from: data)
}
catch {
}
Note that your json is array not dictionary!

How to parse json in swift (convert json string to string)

I don't find a way to parse a simple json object into a string object in swift. I have a network request which gives me this json response:
"\"asdf\""
When I try to parse this into a string in swift it looks like this:
"\"asdf\""
according this documentation from apple I should only need to do this:
Apple Swift documentation
let jsonValue = responseData as? String
But that does not work for me.
I need just asdf as string value.
Can anyone help me out?
Thanks in advance.
EDIT:
Here is my network request code:
let stringUrl = "https://test.fangkarte.de/v1.3/test"
let url = URL(string: stringUrl)!
let request = URLRequest(url: url)
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
if let data = data {
let json = String(data: data, encoding: String.Encoding.utf8)
let response = response as! HTTPURLResponse
if 200...299 ~= response.statusCode {
callback(true, response.statusCode, json!)
} else {
callback(false, response.statusCode, json!)
}
}
})
task.resume()
The value of the variable json is "\"testString\"" and not "testString"
You could try something like:
func parseJSON(_ data: Data) -> [String: Any]? {
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let body = json["data"] as? [String: Any] {
return body
}
} catch {
print("Error deserializing JSON: \n\(error)")
return nil
}
return nil
}
To use:
let data = <variable holding JSON>.data(using: .utf8)
let jsonResult = parseJSON(data)
You get a json string so you can try
let jsonstring = "\"asdf\""
let data = jsonstring.data(using: .utf8)
do {
if let str = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? String {
print(str)
}
}
catch let caught as NSError
{
}

How to fetch JSON data from a url using URLSession?

I am working on an iOS application in which I have to fetch data from this url .
As I can see this url contain JSON data so here should I need to parse it or not I am not getting it how to get this JSON data.
Here is my code.
import UIKit
import SwiftyJSON
typealias ServiceResponse = (ApiResponseData, NSError?) -> Void
class ApiManager: NSObject {
var session:URLSession? = nil
var urlRequest:URLRequest? = nil
override init(){
super.init()
urlRequest = URLRequest(url: URL(string:"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json")!)
urlRequest?.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
session = URLSession(configuration: .default)
}
func callRestApiToFetchDetails(onCompletion: #escaping ServiceResponse) {
let task = session?.dataTask(with: urlRequest!, completionHandler: {data, response, error -> Void in
print("Response = \(data)")
do {
let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
// Do Stuff
print("\(jsonData)")
} catch {
// handle error
print("Error in parsing - \(error)")
}
})
task?.resume()
}
}
But I am getting error in parsing.
You web service response is String.Encoding.ascii that convert into
String.Encoding.utf8 after you have to convert through
NSDictionary JSONSerialization.
Try this method to work.
let url = "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"
URLSession.shared.dataTask(with: URL(string: url)!) { (data, res, err) in
if let d = data {
if let value = String(data: d, encoding: String.Encoding.ascii) {
if let jsonData = value.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: Any]
if let arr = json["rows"] as? [[String: Any]] {
debugPrint(arr)
}
} catch {
NSLog("ERROR \(error.localizedDescription)")
}
}
}
}
}.resume()

How to send array by POST method to server?

I am trying to send array as parameter to server but server is not receiving. Server have to receive two arrays that I am sending. But in server they are not appear ?? I dont know is it my mistake or mistake in the server ??
My array name is testAns and testQuest and I have to send it to parameters: answer and quest.
my Code:
let userID = UserDefaults.standard.string(forKey: "userID")
let artID = UserDefaults.standard.string(forKey: "index")
let myUrl = URL(string: "http://www.someurls.kz/modules/CheckTestF.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
var testAns = [Int]()
var testQuest = [Int]()
testAns = [131,123,23]
testQuest = [123,233,232]
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer=\(testAns)&quest=\(testQuest)"
print(postString)
print(testAns,testQuest)
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
do {
_ = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
}
catch {
print(error)
}
}
task.resume()
}
i don't know how to encode that array on your server side.
but temporary you can try this way and check your database.
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer[0]=131&answer[1]=123&quest[0]=123&quest[1]=233"
You can use the Alamofire that is very popular at this time that is advanced version of AFNetworking
Also, I am sharing the method that will help you to hit API, You have to pass only the dictionary object in this method and this will give you the response in two blocks and you can use them as per requirements.
1: unReachable()
2: handler(responseDict)
//MARK: *********** HIT POST SERVICE IN JSON FORM***********
func hitPostServiceJsonForm(_ params:Dictionary<String,Any>,unReachable:(() -> Void),handler:#escaping ((Dictionary<String,Any>?) -> Void)) {
if networkReachable() == false {
unReachable()
}
let BASE_URL = "http://mydoamain"
var request = URLRequest(url: URL(string: BASE_URL)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
print(BASE_URL)
Alamofire.request(request).responseJSON { response in
//print("Request: \(String(describing: response.request))") // original url request
//print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print("Json Response: \(jsonDict)") // serialized json response
handler(jsonDict)
}
else{
handler(nil)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
handler(nil)
print(error)
break
}
}
}
func networkReachable() -> Bool {
return (NetworkReachabilityManager()?.isReachable)!
}
convert the your array to json string then try to send it to server
func post_array(){
let userID = UserDefaults.standard.string(forKey: "userID")
let artID = UserDefaults.standard.string(forKey: "index")
let myUrl = URL(string: "http://www.someurls.kz/modules/CheckTestF.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
var testAns = [Int]()
var testQuest = [Int]()
testAns = [131,123,23]
testQuest = [123,233,232]
var tempAns : NSString = ""
do {
let arrJson = try JSONSerialization.data(withJSONObject: testAns, options: .prettyPrinted)
let string = NSString(data: arrJson, encoding: String.Encoding.utf8.rawValue)
tempAns = string! as NSString
}catch let error as NSError{
print(error)
}
var tempQuest : NSString = ""
do {
let arrJson = try JSONSerialization.data(withJSONObject: testQuest, options: .prettyPrinted)
let string = NSString(data: arrJson, encoding: String.Encoding.utf8.rawValue)
tempQuest = string! as NSString
}catch let error as NSError{
print(error)
}
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer=\(tempAns)&quest=\(tempQuest)"
print(postString)
print(testAns,testQuest)
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
do {
_ = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
}
catch {
print(error)
}
}
task.resume()
}

A JSON parsing error occurred, here are the details:

Code
func callAddWithPOST(Name mname:String, PhoneNo mphone:String, Email memail:String, Comment mcomments:String){
var names = [String]()
let login = ["countryId":"1"]
print("Your Result is : = \(login)")
let url = NSURL(string: "http://photokeeper.mgtcloud.co.uk/commonwebservice.asmx/getStateList")!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
do {
let auth = try NSJSONSerialization.dataWithJSONObject(login, options: .PrettyPrinted)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = auth
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let badJsonString = "This really isn't valid JSON at all"
let badJsonData = badJsonString.dataUsingEncoding(NSUTF8StringEncoding)!
do {
let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
print(parsed)
let otherParsed = try NSJSONSerialization.JSONObjectWithData(badJsonData, options: NSJSONReadingOptions.AllowFragments)
}
catch let error as NSError {
print("A JSON parsing error occurred, here are the details:\n \(error)")
}
print("Done.")
})
task.resume()
} catch {
print("Error")
}}
OUTPUT
{
d = "{\"result\":[{\"stateId\":3871,\"stateName\":\"Aberdeenshire\"},{\"stateId\":3872,\"stateName\":\"Anglesey/Sir Fon\"},{\"stateId\":3873,\"stateName\":\"Angus\"},{\"stateId\":3874,\"stateName\":\"Antrim\"},{\"stateId\":3875,\"stateName\":\"Argyll And Bute\"},{\"stateId\":3876,\"stateName\":\"Armagh\"},{\"stateId\":3877,\"stateName\":\"Ayrshire\"},{\"stateId\":3878,\"stateName\":\"Bedfordshire\"},{\"stateId\":3879,\"stateName\":\"Berkshire\"},{\"stateId\":3880,\"stateName\":\"Blaenau Gwent/Blaenau Gwent\"},{\"stateId\":3881,\"stateName\":\"Bristol\"},{\"stateId\":3882,\"stateName\":\"Buckinghamshire\"},{\"stateId\":3883,\"stateName\":\"Caerphilly/Caerffili\"},{\"stateId\":3884,\"stateName\":\"Cambridgeshire\"},{\"stateId\":3885,\"stateName\":\"Cardiff/Caerdydd\"},{\"stateId\":3886,\"stateName\":\"Cardiganshire/Ceredigion\"},{\"stateId\":3888,\"stateName\":\"Carmarthenshire/Sir Gaerfyrddin\"},{\"stateId\":3890,\"stateName\":\"Cheshire\"},{\"stateId\":3891,\"stateName\":\"Clackmannanshire\"},{\"stateId\":3893,\"stateName\":\"Conwy/Conwy\"},{\"stateId\":3895,\"stateName\":\"County Durham\"},{\"stateId\":3896,\"stateName\":\"Cumbria\"},{\"stateId\":3897,\"stateName\":\"Denbighshire/Sir Ddinbych\"},{\"stateId\":3898,\"stateName\":\"Derbyshire\"},{\"stateId\":3899,\"stateName\":\"Devon\"},{\"stateId\":3901,\"stateName\":\"Dorset\"},{\"stateId\":3902,\"stateName\":\"Down\"},{\"stateId\":3904,\"stateName\":\"Dumfries And Galloway\"},{\"stateId\":3905,\"stateName\":\"Dunbartonshire\"},{\"stateId\":3906,\"stateName\":\"Dundee\"},{\"stateId\":3907,\"stateName\":\"Durham/North Yorkshire\"},{\"stateId\":3908,\"stateName\":\"East Lothian\"},{\"stateId\":3909,\"stateName\":\"East Sussex\"},{\"stateId\":3910,\"stateName\":\"East Yorkshire\"},{\"stateId\":3911,\"stateName\":\"Edinburgh\"},{\"stateId\":3912,\"stateName\":\"Essex\"},{\"stateId\":3913,\"stateName\":\"Fermanagh\"},{\"stateId\":3914,\"stateName\":\"Fife\"},{\"stateId\":3915,\"stateName\":\"Flintshire/Sir Fflint\"},{\"stateId\":3917,\"stateName\":\"Glamorgan/Morgannwg\"},{\"stateId\":3918,\"stateName\":\"Glasgow\"},{\"stateId\":3919,\"stateName\":\"Gloucestershire\"},{\"stateId\":3920,\"stateName\":\"Gwynedd/Gwynedd\"},{\"stateId\":3921,\"stateName\":\"Hampshire\"},{\"stateId\":3922,\"stateName\":\"Herefordshire\"},{\"stateId\":3923,\"stateName\":\"Hertfordshire\"},{\"stateId\":3924,\"stateName\":\"Highland\"},{\"stateId\":3925,\"stateName\":\"Kent\"},{\"stateId\":3929,\"stateName\":\"Lanarkshire\"},{\"stateId\":3930,\"stateName\":\"Lancashire\"},{\"stateId\":3932,\"stateName\":\"Leicestershire\"},{\"stateId\":3935,\"stateName\":\"Lincolnshire\"},{\"stateId\":3936,\"stateName\":\"London\"},{\"stateId\":3937,\"stateName\":\"Londonderry\"},{\"stateId\":3940,\"stateName\":\"Manchester\"},{\"stateId\":3943,\"stateName\":\"Merthyr Tydfil/Merthyr Tydfil\"},{\"stateId\":3944,\"stateName\":\"Midlothian\"},{\"stateId\":3946,\"stateName\":\"Monmouthshire/Sir Fynwy\"},{\"stateId\":3947,\"stateName\":\"Moray\"},{\"stateId\":3948,\"stateName\":\"Neath Port Talbot\"},{\"stateId\":3949,\"stateName\":\"Newport\"},{\"stateId\":3950,\"stateName\":\"Norfolk\"},{\"stateId\":3951,\"stateName\":\"Northamptonshire\"},{\"stateId\":3952,\"stateName\":\"Northumberland\"},{\"stateId\":3953,\"stateName\":\"Nottinghamshire\"},{\"stateId\":3955,\"stateName\":\"Orkney\"},{\"stateId\":3956,\"stateName\":\"Oxfordshire\"},{\"stateId\":3957,\"stateName\":\"Pembrokeshire/Sir Benfro\"},{\"stateId\":3958,\"stateName\":\"Perth And Kinross\"},{\"stateId\":3959,\"stateName\":\"Powys/Powys\"},{\"stateId\":3960,\"stateName\":\"Renfrewshire\"},{\"stateId\":3962,\"stateName\":\"Rutland\"},{\"stateId\":3963,\"stateName\":\"Scottish Borders\"},{\"stateId\":3964,\"stateName\":\"Shetland Isles\"},{\"stateId\":3965,\"stateName\":\"Shropshire\"},{\"stateId\":3967,\"stateName\":\"Somerset\"},{\"stateId\":3968,\"stateName\":\"South Yorkshire\"},{\"stateId\":3969,\"stateName\":\"Staffordshire\"},{\"stateId\":3970,\"stateName\":\"Stirling\"},{\"stateId\":3971,\"stateName\":\"Suffolk\"},{\"stateId\":3972,\"stateName\":\"Surrey\"},{\"stateId\":3973,\"stateName\":\"Swansea\"},{\"stateId\":3975,\"stateName\":\"Torfaen\"},{\"stateId\":3976,\"stateName\":\"Tyrone\"},{\"stateId\":3977,\"stateName\":\"Warwickshire\"},{\"stateId\":3979,\"stateName\":\"West Lothian\"},{\"stateId\":3980,\"stateName\":\"West Midlands\"},{\"stateId\":3981,\"stateName\":\"West Sussex\"},{\"stateId\":3982,\"stateName\":\"West Yorkshire\"},{\"stateId\":3983,\"stateName\":\"Western Isles\"},{\"stateId\":3987,\"stateName\":\"Wiltshire\"},{\"stateId\":3988,\"stateName\":\"Worcestershire\"},{\"stateId\":3989,\"stateName\":\"Wrexham\"}],\"status\":\"success\"}";
}
A JSON parsing error occurred, here are the details:
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
Done.
I AM GETTING ERROR - Invalid value around character 0. I want to get data in proper format with desired key and value, will anybody please help me to fix this issues.
Your JSON response is corrupted. Use JSONLint to verify it.
Convert it from
{\"result\":[{\"stateId\":3871,\"stateName\":\"Aberdeenshire\"}
to
{
"result": {
"stateId": 3871,
"stateName": "Aberdeenshire"
}
}
Notice the removal of the backslashes.
Looks like you are getting String in your response, so try something like this.
do {
let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject]
let responseStr = parsed["d"] as! String
let correctData = responseStr.dataUsingEncoding(NSUTF8StringEncoding)
let responseDic = try NSJSONSerialization.JSONObjectWithData(correctData, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject]
print(responseDic)
}
catch let error as NSError {
print("A JSON parsing error occurred, here are the details:\n \(error)")
}
Try this,
if let result:String = parsed["d"]! {
let result = convertStringToDictionary(text: result)
print("Converted result = \(result)")
}
//SWIFT 3
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.data(using: String.Encoding.utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
//SWIFT 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}

Resources