carson-katri / swift-request

Declarative HTTP networking, designed for SwiftUI
MIT License
727 stars 41 forks source link

Json: Access nested optional value #28

Closed danousna closed 4 years ago

danousna commented 4 years ago

Hi there,

Thanks for the library.

I am using an api which returns the following json :

{
  "object": {
     "name": "Bob",
        // ...
  },
  "some": "other value"
}

The object key can sometimes be empty.

However, I want to access the name key using my Json object. But when the object is empty, my app crashes because of course, it cannot get to the name key (Could not cast value of type 'NSNull' (0x...........) to 'NSDictionary').

I can't figure out how to test for this.

Thanks for the help.

carson-katri commented 4 years ago

Is using Codable an option? If so you could mark object as optional:

struct MyData : Codable {
  let object: Object?
  let some: String

  struct Object : Codable {
    let name: String
    // ...
  }
}

Then Request can handle decoding it for you

danousna commented 4 years ago

Indeed it works.

Thanks for the help !