Bird
0
0

You have a JSON with nested keys like {"user": {"id": 1, "name": "Bob"}}. How can you decode the nested 'name' using a custom decoder configuration in Swift?

hard📝 Application Q8 of 15
iOS Swift - Networking
You have a JSON with nested keys like {"user": {"id": 1, "name": "Bob"}}. How can you decode the nested 'name' using a custom decoder configuration in Swift?
AUse nested containers in init(from decoder: Decoder) to decode 'name' inside 'user' key
BAdd 'user.name' as a case in CodingKeys enum
CDecode 'name' directly without any special handling
DUse a flat struct without nested decoding
Step-by-Step Solution
Solution:
  1. Step 1: Recognize nested JSON structure

    The 'name' key is inside the 'user' object, so direct decoding won't work.
  2. Step 2: Use nested containers in custom init

    Implement init(from decoder: Decoder) and use nestedContainer(keyedBy:forKey:) to access nested keys.
  3. Final Answer:

    Use nested containers in init(from decoder: Decoder) to decode 'name' inside 'user' key -> Option A
  4. Quick Check:

    Nested JSON requires nested containers decoding [OK]
Quick Trick: Use nestedContainer to decode nested JSON keys [OK]
Common Mistakes:
  • Trying to flatten nested keys in CodingKeys
  • Ignoring nested structure causing decoding failure
  • Assuming direct decoding works for nested keys

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes