-2

I need a way to decode JSON into Swift structure, but start decoding not from top level of JSON.

For example, I have some JSON response like this

{"response": { "name": "John", "id": 2"} }

Actually, I need only need the nested object with name and id fields, I do not need top level "response" in my struct.

So the question is:
Can I decode that nested object without "response" top level?
But it would be good, if I can check, if this top level "response" exists, and then decode.

My API returns either top level "response" with response object inside or top level "error" with error object inside, so I have to check if there is error or response before decoding.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
cyrmax
  • 1

2 Answers2

1

You need to include everything but if you don't want to create a struct from the top level you could decode it as a dictionary

struct Person: Decodable {
    let id: Int
    let name: String
}

do {
    let result = try JSONDecoder().decode([String: Person].self, from: data)
    
    if let response = result["response"] {
        print(response)
    } else if let error = result["error"] {
        print(error)
    } else {
        print("Unknown result from API call")
    }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
-1

You can try to use ObjectMapper and doing this: Mapping of Nested Objects

func mapping(map: Map) {
    name <- map["response.name"]
    id   <- map["response.id"]
}
Hai Pham
  • 193
  • 5