bignerdranch / Freddy

A reusable framework for parsing JSON in Swift.
MIT License
1.09k stars 119 forks source link

How to read an array of dictionaries? #211

Closed kgrigsby59 closed 8 years ago

kgrigsby59 commented 8 years ago

I have the following JSON

[
  {
    "search": "one",
    "replacement": "1"
  },
  {
    "search": "two",
    "replacement": "2"
  }
]

and want to read it into an array of HTMLReplacementCriteria

            struct HTMLReplacementCriteria: JSONDecodable {
                let search: String
                let replacement: String

                init(json: JSON) throws {
                    search = try json.string("search")
                    replacement = try json.string("replacement")
                }

Is there a method on JSON that can take my type (HTMLReplacementCriteria) and return an array of them or must the top level be a dictionary?

jgallagher commented 8 years ago

I believe you want yourJSON.arrayOf(type: HTMLReplacementCriteria.self).

mdmathias commented 8 years ago

Yep! See the README and the tests for examples (particularly JSONSubscriptingTests.swift).

kgrigsby59 commented 8 years ago

@jgallagher Thank You! @mdmathias I did look in both both places before posting. I don't see any references to 'arrayOf' in the README and the JSONSubscriptingTests.swift only use the arrayOf("residents", type: Resident.self) method. I didn't look closely enough at the arrayOf documentation to see that the first parameter can be omitted.

mdmathias commented 8 years ago

@kgrigsby59 The README and the tests give examples of accomplishing the same goal using a variety of approaches. Nonetheless, arrayOf is certainly a good way to go!

For example, I linked to the following in the README:

let data = getSomeData()
do {
    let json = try JSON(data: data)
    let people = try json.array("people").map(Person.init)
    // do something with `people`
} catch {
    // do something with the error
}
edasque commented 8 years ago

Sorry, I must be missing something but I don't get it. In:

            let json = try JSON(jsonString: the_jsonString as String)

json has no array or arrayOf method in Freddy 3.0 AFAIK.

I haven't found how to map a JSON file (to an array of my StockQuote structures) when the root of the JSON is an array and not a dictionary. Obviously json.decodedArray(at:"") does not work.

@mdmathias can you point at what I am missing?