简体   繁体   中英

How to parse json string array with not knowing how many strings there are in Swift

I want to parse one json than have an array with multiple strings, but i don't know how to do. I know how to parse json but in static method but i don't know if I've multiple string

My json is:

{
    "index": [
        {
            "numberOfString":"N"
            "string1":"myString1",
            "string2":"myString2",
            "stringN":"mystringN"
        }
    ]
}

If the number of strings is unknown or can change you can decode this to a dictionary. The struct for this would be:

struct Response: Codable{
    var index: [[String:String]]
}

In your example the index var contains an array of [String:String] .


Edit:

As you asked for an example:

I don´t know what you want to do with this and don´t know where this json comes from (file/dataStream) so it will be just a general example.

Let´s say you get this as Data then the next step would be to decode it.

let response = try JsonDecoder().decode(Response.self, from: data)

this will lead to an object with a structure described in my initial answer. Now you can iterate over the dictionary in the response and map the values to an array for example. This could be used in a tableview for presenting.

let arr = response.index.map{ $1 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM