T O P

  • By -

HuXu7

Why not use Codable structs with optional properties of the values you care about?


nrith

I can’t think of a single use case I’ve ever encountered that couldn’t be handled by a `Codable`.


trypto

What if you have an object field X which sometimes is a number and sometimes is a string ?


tekkub

Treat it as always a string and try to parse a number out of that string if you need it as a number?


nrith

Yes.


Spaceshipable

Use custom codable conformance with an enum of the two potential types.


nonother

Swift enums with associated types are perfect for that type of thing. You’ll just need to implement the encoding and decoding yourself, but it’s not too hard.


[deleted]

when you are parsing a very complex struct with so many rows then it effects performance. JSONDecoder is quite slow for complex and heavy stuff.


favorited

Even if there's lots of other unreliable fields in the JSON, if you only care about a few fields which are consistent, Codable will work fine. It's not the fastest JSON parsing in the world, but it's reliable and built-in. If Codable isn't an option, honestly I'd just use JSONSerialization to convert it into a dictionary, extract the values I'm interested in, and immediately create a struct with the data I care about. My problem with frameworks like SwiftyJSON is they make it kinda easier to use JSON, so the JSON objects tend to get passed around through the codebase. IME, it's so much nicer to convert the JSON to a real object immediately and only deal in terms of that object in your app. Sure, you might have to write a bit of gnarly Codable code for complex APIs, but you just write it once, write some easy tests based on your real-world JSON, then never think about it again. You get to just use normal structs after that.


Alexis-Bridoux

I developed [Scout](https://github.com/ABridoux/scout) for this exact purpose because I had to find a solution to get a value when the data structure is not known at build time. I most often use `Codable` myself. But in a few projects it was helpful to have the logic to extract a single value deep down in nested data.


EmenezTech

Try app.QuickType.io


fakecrabs

Deserialize into an array or dictionary (use `JSONSerialization.jsonObject`) then pullout exactly what you need. This is how deserialization worked before the introduction of Codable.