Swift JSON




Sending HTTP POST Body


    func requestUser(completion: @escaping(User) -> Void){
        let url = URLBuilder.user()
        var request = URLRequest(url:url)
        var jsonData = Data()

        request.httpMethod = "POST"
        request.addValue("application/json",forHTTPHeaderField: "Content-Type")
        request.addValue("application/json",forHTTPHeaderField: "Accept")
        do {
            /* encodeing convert object to JSON */
            print("attempting to encoded userDict")
            let jsonEncoder = JSONEncoder()
            jsonData = try jsonEncoder.encode(user)
            print("successfully encoded userDict")
            print("jsonData:   ", jsonData)

        } catch{print("Failed to serialize ...")}      
        request.httpBody = jsonData
        let task = session.dataTask(with:request){ (data,response,error) in
            guard let unwrapped_data = data else{print("no data"); return}
            do {
                print("attempting to decode")
                /* decode convert JSON to object */
                let jsonDecoder = JSONDecoder()
                let user_response = try jsonDecoder.decode(User.self, from: unwrapped_data)
                print("** successfullly decoded response")
                OperationQueue.main.addOperation {
            } catch { print("error json-ing"); return}


If this example doesn’t work make sure what you are coding is not nil.



JSON Encoding

struct Dog: Codable {

    var name: String

    var owner: String



// Encode

let dog = Dog(name: "Rex", owner: "Etgar")


let jsonEncoder = JSONEncoder()

let jsonData = try jsonEncoder.encode(dog)

let json = String(data: jsonData, encoding: String.Encoding.utf8)



JSON Decoding

// Decode

let jsonDecoder = JSONDecoder()

let secondDog = try jsonDecoder.decode(Dog.self, from: jsonData)


Source: https://stackoverflow.com/questions/29599005/how-to-serialize-or-convert-swift-objects-to-json


JSON Serialization

What is this

Stackoverflow suggests always use JSONDecoding instead of Serialization


It seems for sending httpbody request you can use jsonEncoding