2
{
    "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.

1 Answer 1

5

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)
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.