Search code examples
swiftalamofire

How to decode non-JSON data using Alamofire library


I have using a API Response that is not in JSON format but wanted to still decode it, what are the ways that can achieve this stage.

Right now the response is failing, Failed to decode JSON: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.

I want to decode regardless of being a non-json response

I tried using replacing =(equals) with : and parsed the JSON and it worked, but after making few changes it stopped working

The Response is in this format

 Data = { "value" = "pair"; "value2" = "pair2"; }

My attempt

let validJSONString = rawString
                       .replacingOccurrences(of: "=", with: ":")
                       .replacingOccurrences(of: "NA", with: "null")
                       .replacingOccurrences(of: ";", with: ",")

Solution

  • One option is to add another replace to get rid of the trailing comma

    .replacing(/,\s*}/, with: "}")
    

    So the whole conversion is

    let validJSONString = rawString
        .replacingOccurrences(of: " =", with: ":")
        .replacingOccurrences(of: "NA", with: "null")
        .replacingOccurrences(of: ";", with: ",")
        .replacing(/,\s*}/, with: "}")