I try to convert Json string (response) to json object but after JSONSerialization the output is not clear

85 Views Asked by At

I got a response from web service and try to work on it to put it in a model, but i can't work with it .

this is the response.string

"{\"USER_NO\":1,\"USER_NAME\":\"المسار البديل لتكنولوجيا المعلومات\",\"TASK_CATEGORY_NO\":1,\"USER_ID_NUMBER\":\"1031523473\",\"Mobile_No\":\"0567123432\"}"

I used extension :

extension String{
func tooDictionary() -> NSDictionary {
    let blankDict : NSDictionary = [:]
    if let data = self.data(using: .utf8)  {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
        } catch {
            print(error.localizedDescription)
        }
    }
    return blankDict
}
}

to convert it to dictionary then put it in object but i failed to do that

i'm sorry but i'm new developer in swift4 ,any help please

and thank

1

There are 1 best solutions below

0
On BEST ANSWER

Use Decodable:

struct User: Decodable {

    private enum CodingKeys : String, CodingKey {
        case userNumber = "USER_NO", taskCategoryNumber = "TASK_CATEGORY_NO"
        case userName = "USER_NAME", userID = "USER_ID_NUMBER", mobileNumber = "Mobile_No"
    }

    let userNumber, taskCategoryNumber: Int
    let userName, userID, mobileNumber : String
}

let jsonString = """
{"USER_NO":1,"USER_NAME":"المسار البديل لتكنولوجيا المعلومات","TASK_CATEGORY_NO":1,"USER_ID_NUMBER":"1031523473","Mobile_No":"0567123432"}
"""

let data = Data(jsonString.utf8)
do {
    let result = try JSONDecoder().decode(User.self, from: data)
    print(result)
} catch { print(error) }

Note: Don't use NSArray / NSDictionary in Swift