Bird
0
0

You have this JSON:

hard📝 Application Q15 of 15
iOS Swift - Networking
You have this JSON:
{"user": {"id": 1, "name": "Bob"}}

And these Swift structs:
struct User: Codable { var id: Int; var name: String }
struct Response: Codable { var user: User }

How do you decode the JSON into a Response object?
AUse JSONSerialization.jsonObject(with: jsonData)
BUse JSONDecoder().decode(User.self, from: jsonData)
CUse JSONDecoder().decode(Response.self, from: jsonData)
DUse JSONEncoder().encode(Response.self, from: jsonData)
Step-by-Step Solution
Solution:
  1. Step 1: Identify the top-level JSON structure

    The JSON has a top-level key "user" matching the Response struct's property.
  2. Step 2: Choose correct decoding target

    To decode the entire JSON, decode to Response.self, which contains User.
  3. Final Answer:

    Use JSONDecoder().decode(Response.self, from: jsonData) -> Option C
  4. Quick Check:

    Decode top-level struct = Use JSONDecoder().decode(Response.self, from: jsonData) [OK]
Quick Trick: Decode to the struct matching JSON root [OK]
Common Mistakes:
  • Decoding to nested User instead of Response
  • Using JSONEncoder instead of JSONDecoder
  • Using JSONSerialization instead of Codable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes