1

Here is my JSON I am trying to parse

{
  "rows": [
    {
      "layout": "Y",
    },
    {
      "layout": "A",
    }
  ]
}

I want to be able to filter out the layout types that are not supported. I am using the JSONDecoder to to convert the JSON data into structs but I am having an issue processing the rows. I am attempting to convert each row using let row = try? rowContainer.decode(Row.self) but I can figure out how to move to the next one if it fails unless I decode it to an empty struct. I tried just decoding it to a Dictionary but it won't except Any for the value field.

enum RowType: String, Codable {
    case a = "A"
    case b = "B"
}

public struct Page: Codable {

    let rows: [Row]

    public init(from decoder: Decoder) throws {

        // Get Container
        let container = try decoder.container(keyedBy: CodingKeys.self)

        // Create Result Array
        var rowResult: [Row] = []

        // Get Rows Container
        var rowContainer = try container.nestedUnkeyedContainer(forKey: .rows)

        // Process Rows
        while !rowContainer.isAtEnd {

            // Create Row
            if let row = try? rowContainer.decode(Row.self) {
                rowResult.append(row)
            }
            else {

                // Increment Row Container
                _ = try rowContainer.decode(Empty.self)
            }
        }

        // Set Result
        rows = rowResult
    }

    // Used For Unsupported Rows
    struct Empty: Codable {}
}

public struct Row: Codable {
    let layout: RowType
}

1 Answer 1

4

This is a different approach.

Create a temporary struct with the layout string value

public struct RawRow: Codable {
    let layout: String
}

In Page first decode rows to RawRow and then compactMap the array to Row. It filters all items whose layout value cannot be converted to the enum

public struct Page: Codable {
    let rows: [Row]

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let rowData = try container.decode([RawRow].self, forKey: .rows)
        rows = rowData.compactMap {
            guard let rowType = RowType(rawValue: $0.layout) else { return nil }
            return Row(layout: rowType)
        }
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Is there any reason in this situation to use the type alias Codable rather than Decodable?
@Marcy No, there's none. Actually Decodable is sufficient. I just copied&pasted the structs.
This is pretty much what I was doing to in my code above but I was trying to avoid having an extra struct like that but thank you for your reply
Isn't Empty an extra struct as well? 😉
Yeah thats what I am trying to get rid of
|

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.