Closed trispo closed 8 years ago
You probably want arrayOf
or map
:
let json = try JSON(... your data...)
let models1 = try json.arrayOf(type: Model.self)
let models2 = try json.array().map(Model.init)
class GitHubIssue138Example: XCTestCase {
struct Model: JSONDecodable {
let identifier: String
let name: String
let image: String
init(json value: JSON) throws {
identifier = try value.string("identifier")
name = try value.string("name")
image = try value.string("image")
}
}
func testDecodingArrayOfModel() {
let jsonStr = "[\n {\n \"identifier\": \"id 1\",\n \"name\": \"name 1\",\n \"image\": \"path 1\"\n },\n {\n \"identifier\": \"id 2\",\n \"name\": \"name 2\",\n \"image\": \"path 2\"\n }\n ]"
let JSON = try! Freddy.JSON(jsonString: jsonStr)
let models: [Model]?
switch JSON {
case let .Array(jsonModels):
models = try? jsonModels.map { try Model.init(json: $0) }
default:
models = nil
}
XCTAssertNotNil(models)
}
}
Ah. Thanks. Didn't see that .array() can be called without parameters.
Hey guys,
Is this still valid syntax? Assuming data is of type Data:
let json = try JSON(data: data)
let models2 = try json.array().map(Model.init)
Keeping getting "Enum element 'array' cannot be referenced as an instance member".
This changed with Swift 3. Try .getArray()
instead of .array()
.
Could anything be done to make Xcode suggest .getArray()
? When I type myJSON.arra
, the suggestions I get are getArray(at: ...
and decodeArray(at: ...
which had me trying silly things like myJSON.getArray(at: "")
until I found this thread.
Just a small improvement that would help, if it's even possible with Xcode's suggestion handling.
AFAIK we have no way of influencing Xcode suggestions. :(
I had a similar issue to RickDT, also solved by reading this thread. Thanks very much. 👍
I'm trying to decode json with a root array containing dictionaries like this:
How would I map those dictionaries into model structs?