-1

I would like to decode this JSON using codingkeys and decoder methods in my Swift code. I would rather just create two data models : Photos that contains the page information and the array of type Photo and not have to create another type.

I tried different methods given online but couldn't get it to work for this scenario. Can I do this short of doing it manually? My response is decoded automatically on Alamofire side and I would love to keep it that way.

{
"photos":
{
    "page": 1,
    "pages": 2234,
    "perpage": 1,
    "total": 223368,
    "photo":
    [
        {
            "id": "51854706028",
            "owner": "193539154@N05",
            "secret": "c09e67936d",
            "server": "65535",
            "farm": 66,
            "title": "Window",
            "ispublic": 1,
            "isfriend": 0,
            "isfamily": 0
        }
    ]
},
"stat": "ok"
}
Anton Unt
  • 1,835
  • 1
  • 21
  • 47
  • 2
    Could you clarify with your current code? It's unclear what you want to discard. – Larme Feb 01 '22 at 14:52
  • {"photos": . I would like to discard this from the top and "stat" from the bottom – Anton Unt Feb 01 '22 at 22:22
  • You can use a custom decoding `init(from decoder: Decoder)` to handle such case, but that's work. I'd recommend to use two structs, but make the unwanted one private/"hidden" to higher level methods. – Larme Feb 01 '22 at 22:30

1 Answers1

0

In this kind of situation I think it's best to accept the restrictions of Codable in order to get the benefit of the automatic coding/decoding provided. You could work really hard to find a manual solution and then have to maintain that going forward, but in the end what do you get from doing that?

(Not sure where you've got to with your types, but I would go for three types here: PhotosResponse and Photo, both conforming to Codable (Decodable if you're only going one way), and then a PhotosMetadata type which takes a PhotosResponse instance and grabs just the values you need.)

adamjansch
  • 1,170
  • 11
  • 22