Search code examples
jsonswiftmultipartform-data

Swift: Convert Dictionary into JSON for multipart/Form-Data


I have a swift app, that makes requests to the servers with both normal values and Images, so I am using a multipart/form-data request. I have an object that has all my values like below:

 struct parameters: Codable {
     var request : String = "blah"
     var arrayData : [String] = ["bleh", "bluh"]
     var dictionaryData : [String: String] = ["1": "Blah", "2": "Blah"]
 }

However, I am having trouble inserting the json converted version of the arrays and dictionaries into the httpBody. I've tried using JSONEncoder(), but that converts the entire object into JSON, and I can't insert boundaries and other things. Is there any way to convert just the arrays & dictionaries into json format which I can then insert as the values in a multipart/form-data request.

For example, for the string, dictionary, and array it would return

 "blah"
 ["bleh", "bluh"]
 {"1": "Blah", "2": "Blah"}

Solution

  • You can just encode the individual components separately, rather than the struct as a whole. Using the above example:

    let paramters = Parameters()
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    let request = try! encoder.encode(paramters.request)
    let array = try! encoder.encode(paramters.arrayData)
    let dict = try! encoder.encode(paramters.dictionaryData)
    

    which will give you the components individually, and you can then access them and use them however you fancy. As a trivial example:

    print("Request \n", String(data: request, encoding: .utf8)!, "\n\n")
    print("Array \n", String(data: array,encoding: .utf8)!, "\n\n")
    print("Dict \n", String(data: dict ,encoding: .utf8)!, "\n\n")
    

    Outputting...

    Request

    "blah"

    Array

    [ "bleh", "bluh" ]

    Dict

    { "2" : "Blah", "1" : "Blah" }