简体   繁体   中英

Swift - How to convert Struct to Dictionary

Question updated

This is my RequestModel

    enum RequestHTTPMethod: String {
    case get = "GET"
    case post = "POST"
}

class RequestModel: NSObject, Codable {
    
    // MARK: Properties
    
    var path: String {
        return ""
    }
    
    var parameters: [String: Any?] {
        return [:]
    }
    
    var headers: [String: String] {
        return [
            "Content-Type": "application/json",
            "Authorization": "Bearer  Token",
        ]
    }
    
    var method: RequestHTTPMethod {
        return body.isEmpty ? RequestHTTPMethod.get : RequestHTTPMethod.post
    }
    
    var body: [String: Any?] {
        return [:]
    }
}

// MARK: - public func

extension RequestModel {
    
    func urlRequest() -> URLRequest {
        var endpoint: String = Constant.ServiceConstant.baseURL.appending(path)
        
        for parameter in parameters {
            if let value = parameter.value as? String {
                endpoint.append("?\(parameter.key)=\(value)")
            }
        }
        
        var request: URLRequest = URLRequest(url: URL(string: endpoint)!)
        
        request.httpMethod = method.rawValue
        
        for header in headers {
            request.addValue(header.value, forHTTPHeaderField: header.key)
        }
        
        if method == RequestHTTPMethod.post {
            do {
                request.httpBody = try JSONSerialization.data(withJSONObject: body, options: JSONSerialization.WritingOptions.prettyPrinted)
            } catch let error {
                // TODO: Handle Error
                print("error = \(error.localizedDescription)")
            }
        }
        return request
    }
}

this is my createPersonRequestModel

class CreatepersonRequestModel: RequestModel { 

let person = Person(name: "User", age: 23, Hobby: Hobby(name: "football", place: "Stadium"))


override var path: String {
        return Constant.ServiceConstant.createPerson
    }

override var body: [String : Any?] { 
   PersonToBody()
}

    func PersonToBody() -> [String: Any] { 
    
            let encoder = JSONEncoder()
            encoder.outputFormatting = .prettyPrinted
            encoder.dateEncodingStrategy = .iso8601
    
            guard let insectData = try? encoder.encode(person),
                  let jsonString = String(data: insectData, encoding: .utf8) else { return [:] }
    
            if let data = jsonString.data(using: .utf8) {
                do {
                    guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] else { return [:] }
                    return json
                } catch {
                    print("Something went wrong :(")
                }
            }
            return [:]
    }

I've one Person struct

    struct Person: Codable {
    var name: String
    var age: Int
    var hobby: Hobby
}

struct Hobby: Codable {
    var name: String
    var place: String
}

and The code resulting from the convert ->

   ["hobby": Optional({
    name = football;
    place = Stadium;
    }), "age": Optional(23),
     "name": Optional(User)]

I convert the person object in the createPersonRequestModel file to the [String: Any] type and put it in the body I received from RequstModel and overriden, but the request I send fails due to the data in the body. How can I fix this problem?

You need

do {
     let encoder = JSONEncoder()
     encoder.outputFormatting = .prettyPrinted
     encoder.dateEncodingStrategy = .iso8601
     request.httpBody = try encoder.encode(person)  
}
catch {
  print(error)
}

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