-
-
Notifications
You must be signed in to change notification settings - Fork 198
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Returning some of a JSON array #124
Comments
you could write your own parser to handle this. It would look a lot like the built in Array parser, but with public func decodePartialArray<A where A: Decodable, A == A.DecodedType>(value: JSON) -> Decoded<[A]> {
switch value {
case let .Array(a): return catOptionals(A.decode <^> a)
default: return .TypeMismatch("\(value) is not an Array")
}
}
func catOptionals<T>(xs: [T?]) -> [T] {
return xs.reduce([]) { accum, elem in
return elem.map { accum + [$0] } ?? accum
}
} Then, in your j <| "photos" >>- decodePartialArray |
Yes, it's doable, but you might want to look into why you have partial information about a photo. If it's just because you're dealing with bad data that you don't have control over then that's one thing but if you do control that then fixing the data source to return full or no data for an image might be easier and more reliable. |
You'll need to wrap that successful |
Ah yes, that would work. Tony: In this one case I have control over the API, but on most client projects I don't so I was curious. Thanks again! |
Let's say the server returns a JSON array of photos. Each photo should have an ID, a URL, and maybe the name of the person who took it.
Now, we don't wanna show a photo in the app if info is missing. A photo without the author's name breaks things, so I don't wanna mark it as optional. However, in it's current form, the decode function would return nil if one photo out of 20 were missing the name.
How complicated would it be to make decode return the 19 valid photos and maybe have information somewhere to say "this one photo was invalid" instead of showing 0 photos in the app when 19 are totally fine to show?
The text was updated successfully, but these errors were encountered: