4

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.

3
  • 1
    your json string doesn't conform to specification, check json.org Commented Jun 17, 2017 at 10:31
  • Then How to generate json String Commented Jun 17, 2017 at 10:33
  • see the answer. just create the string from data representation Commented Jun 17, 2017 at 10:45

2 Answers 2

2

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"
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Alwin there are tons of 'the same' questions and answers on stackoverflow, next try to find the answer first.
okey I tried but I can't find. Next time I will improve keywords of search.
0

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
    }

1 Comment

yes my bad, json is a text format I mean to say that it has to be array or dictionary structure json.org

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.