1

My app parses a number of APIs in Swift some of which share similar names for dictionaries and/or arrays.

I can't control the names of the incoming JSON dictionaries arrays as they come from API endpoints. Currently I have one utility class that processes all these APIs. How can I parse APIs that share common names?

Here is what I'm using for one API.

 struct aVideo: Codable {
        let page, totalResults, totalPages: Int
        let results: [Result]
        
        enum CodingKeys: String, CodingKey {
            case page
            case results
        }
    }
    
    // MARK: - Result
    struct Result: Codable {
        let popularity: Double
        let voteCount: Int
        let video: Bool
    }

This other API uses the same key, Result and it is throwing an error.

// MARK: - WordInfo
    struct WordInfo: Codable {
        let word: String
        let results: [Result]
        let frequency: Double
    }

     // MARK: - Result
    struct Result: Codable {
        let definition, partOfSpeech: String
        let synonyms, entails, hasTypes, derivation: [String]
    }

Thanks for any suggestions.

1 Answer 1

2

The JSON itself doesn't define the name of the structure -- only the name of the property that holds it, so you're safe to redefine the names of your structs as needed:

struct WordInfo: Codable {
        let word: String
        let results: [WordInfoResult]
        let frequency: Double
    }

     // MARK: - Result
    struct WordInfoResult: Codable {
        let definition, partOfSpeech: String
        let synonyms, entails, hasTypes, derivation: [String]
    }

The decoder will know that when it gets to results on WordInfo that it should be parsed as the type [WordInfoResult] because that's how you've defined it.

Sign up to request clarification or add additional context in comments.

Comments

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.