Home > Back-end >  Convert JSON to Array Xcode
Convert JSON to Array Xcode

Time:06-15

I am trying to implement two side by side UIPickerViews, one for Type and the other for Subtype. Each is an array of strings

var typePickerData: [String] = [String]()
var subtypePickerData: [String] = [String]()

Each is a pretty simple array of names:

typePickerData = ["Monitor","Keyboard","Mouse"]

When the viewDidLoad fires or when a new Type is selected, the app makes a remote db call and I get a response containing JSON of subtype names which I want to use to populate and reload the subtype picker.

I am stuck on converting the response into subtypePickerData

let decoder = JSONDecoder()
    
if let jsonResponse = try? decoder.decode([String].self, from: data) {
        
    print("parse subtype response \(jsonResponse)")
        
    subtypePickerData = jsonResponse
    DispatchQueue.main.async {
        self.subtypePicker.reloadAllComponents()
    }
}

What am I doing wrong here converting the JSON response to subtypePickerData?

this is what I am getting from the remote call

result Optional(<__NSArrayM 0x281370e70>( { name = Monitor; },{ name = "AV Accessories"; },{ name = Computer; },{ name = "Monitor Stands"; },{ name = "Bracket/Mount"; },{ name = Screen; }

Here is my updated code after solving issue

    let decoder = JSONDecoder()

    if let jsonResponse = try? decoder.decode(Subtypes.self, from: data) {
        SubtypeList = jsonResponse.result
        self.subtypePickerData = SubtypeList.map{$0.Name}
        DispatchQueue.main.async {
            self.subtypePicker.reloadAllComponents()
        }
    }

CodePudding user response:

Yor response seems to be not type of [String] but an array of custom objects. You first need to create a struct to decode your response data to.

struct NameContainer{
    var name: String
}

then do:

//change decoding to String array to decoding array of custom object NameContainer
if let jsonResponse = try? decoder.decode([NameContainer].self, from: data) {
        
    print("parse subtype response \(jsonResponse)")
        
    subtypePickerData = jsonResponse.map{$0.name} // Map your objects to strings and assign them
    DispatchQueue.main.async {
        self.subtypePicker.reloadAllComponents()
    }
}

Remarks:

  • Never use try? this will obfuscate all errors. Use a proper do/catch block, handle the error or mark your function throws and handle the error up the chain.

CodePudding user response:

DispatchQueue.main.async {
    self.subtypePicker.reloadAllComponents()

Bracket/Mount"; },{ name = Screen; } –
  • Related