简体   繁体   中英

How to convert JSON String to JSON Object in swift?

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 .

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

Json has to be in Array or Dictionary, it can't be only string so to create a jsonstring first you need to convert to Data format and then convert to String

   func generateJSONObject() {
       let jsonObject = createJSONObject(firstName: "firstName", middleName: "middleName", lastName: "lastName", age: 21, weight: 82)
       print("jsonObject : \(jsonObject)")

       if let jsonString = convertToJsonString(json: jsonObject), let jsonObjectFromString = convertToDictionary(text: jsonString) {
           print("jsonObjectFromString : \(jsonObjectFromString)")
       }
    }

    func convertToJsonString(json: [String: Any]) -> String? {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
            return String(data: jsonData, encoding: .utf8)
        } catch {
            print(error.localizedDescription)
        }
        return nil
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM