How to convert JSON String to JSON Object in swift?

17,251

based on discussion

import Foundation

let firstName = "Joe"
let lastName = "Doe"
let middleName = "Mc."
let age = 100
let weight = 45

let jsonObject: [String: [String:Any]] = [
    "user1": [
        "first_name": firstName,
        "middle_name": middleName,
        "last_name": lastName,
        "age": age,
        "weight": weight
    ]
]
if let data = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted),
    let str = String(data: data, encoding: .utf8) {
    print(str)
}

prints

{
  "user1" : {
    "age" : 100,
    "middle_name" : "Mc.",
    "last_name" : "Doe",
    "weight" : 45,
    "first_name" : "Joe"
  }
}
Share:
17,251
Alwin
Author by

Alwin

Experienced Fullstack Developer with a demonstrated history of working in the program development industry. Skilled in Flutter, Django, Firebase, iOS Development, Java, Android Development, Web Development, Unity Game Development, and XML. Strong engineering professional who graduated from IES College of Engineering Thrissur.

Updated on June 29, 2022

Comments

  • Alwin
    Alwin almost 2 years

    I trying to generate JSON Object and convert that to JSON String and that process is Successfully placed. But my real problem rises when I try to convert JSON String to JSON Object. When I try I get nil as result.

    func generateJSONObject() {
            let jsonObject = createJSONObject(firstName: firstName[0], middleName: middleName[0], lastName: lastName[0], age: age[0], weight: weight[0])
            print("jsonObject : \(jsonObject)")
    
            let jsonString = jsonObject.description // convert It to JSON String
            print("jsonString : \(jsonString)")
    
            let jsonObjectFromString = convertToDictionary(text: jsonString)
            print("jsonObjectFromString : \(String(describing: jsonObjectFromString))")
    
        }
    

    createJSONObject func

    // JSON Object creation
        func createJSONObject(firstName: String, middleName: String, lastName: String, age: Int, weight: Int) -> [String: Any] {
    
            let jsonObject: [String: Any] = [
                "user1": [
                    "first_name": firstName,
                    "middle_name": middleName,
                    "last_name": lastName,
                    "age": age,
                    "weight": weight
                ]
            ]
            return jsonObject
        }
    

    convertToDictionary func

    func convertToDictionary(text: String) -> [String: Any]? {
            if let data = text.data(using: .utf8) {
                do {
                    return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                } catch {
                    print(error.localizedDescription)
                }
            }
            return nil
        }
    

    Logs

    1. When I print JSON Object I get

    jsonObject : ["user1": ["age": 21, "middle_name": "Lazar", "last_name": "V", "weight": 67, "first_name": "Alwin"]]

    1. When I print JSON String I get

      jsonString : ["user1": ["age": 21, "middle_name": "Lazar", "last_name": "V", "weight": 67, "first_name": "Alwin"]]

    2. Convert JSON String to JSON Object I get below error

      The data couldn’t be read because it isn’t in the correct format.

      jsonObjectFromString : nil

    I don't know why this happening. I want to convert JSON String to JSON Object and I want to parse the JSON.