0

I receive server response which contains geojson I need to have the geojson as string and don't want to decode it, but this code throws type mismatch exception.

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    id_s = try container.decode(String.self, forKey: .id_s)
    name = try container.decode(String.self, forKey: .name)
    description = try container.decode(String.self, forKey: .description)
    area_type = try container.decode(String.self, forKey: .area_type)
    active = String(try container.decode(Bool.self, forKey: .active))
    danger = String(try container.decode(Bool.self, forKey: .danger))
    scheduled_from = try container.decodeIfPresent(String.self, forKey: .scheduled_from)
    scheduled_to = try container.decodeIfPresent(String.self, forKey: .scheduled_to)
    
    let geojsonString = try container.decode(String.self, forKey: .geojson)
    // I need the raw geojson string, not a decoded dictionary
    // I get "Expected to decode String but found a dictionary instead"
}

I tried let geojson = try container.decode(String.self, forKey: .geojson) and et geojson = try container.decode(\[String, Any\].self, forKey: .geojson)

4
  • How about decoding it as a dictionary and then converting it to a string later with JSONSerialization? Commented Jun 25, 2024 at 10:00
  • container.decode([String: Any].self, forKey: .geojson) -> [String: Any] and Any is not codeable. Commented Jun 25, 2024 at 10:07
  • They meant you should use JSONSerialization instead of JSONDecoder. Or you can decode it as normal and then encode the selected part Commented Jun 25, 2024 at 10:10
  • Maybe you should explain why you want to do this and there might be an alternative solution that is better. Commented Jun 25, 2024 at 11:21

0

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.