Pyae Phyoe Shein
Pyae Phyoe Shein

Reputation: 13827

Why SwiftyJSON cannot parse Array String in swift 3

{
    "item": [
        {
            "pid": 89334,
            "productsname": "Long Way",
            "address": "B-4/7, Malikha Housing, Yadanar St., Bawa Myint Ward,",
            "telephone": "[\"01570269\",\"01572271\"]"
        },
        {
            "pid": 2,
            "productsname": "Myanmar Reliance Energy Co., Ltd. (MRE)",
            "address": "Bldg, 2, Rm# 5, 1st Flr., Hninsi St., ",
            "telephone": "[\"202916\",\"09-73153580\"]"
        }
    ],
    "success": true
}

I cannot parse telephone value from above JSON object with following code.

for item in swiftyJsonVar["item"].array! {
    if let jsonDict = item.dictionary {
        let pid = jsonDict["pid"]!.stringValue
        let productsname = jsonDict["productsname"]!.stringValue

        var telephones = [String]()
        for telephone in (jsonDict["telephone"]?.array)! {
            telephones.append(telephone.stringValue)
        }
    }
}

I want to get and display one by one phone number of above JSON. I'm not sure why above code is not working. Please help me how to solve it, thanks.

Upvotes: 2

Views: 309

Answers (1)

Code Different
Code Different

Reputation: 93171

Because telephone is a string that looks like an array, not an array itself. The server encoded this array terribly. You need to JSON-ify it again to loop through the list of telephone numbers:

for item in swiftyJsonVar["item"].array! {
    if let jsonDict = item.dictionary {
        let pid = jsonDict["pid"]!.stringValue
        let productsname = jsonDict["productsname"]!.stringValue

        var telephones = [String]()
        let telephoneData = jsonDict["telephone"]!.stringValue.data(using: .utf8)!
        let telephoneJSON = JSON(data: telephoneData)

        for telephone in telephoneJSON.arrayValue {
            telephones.append(telephone.stringValue)
        }
    }
}

Upvotes: 5

Related Questions