处理嵌套的json数组swift

时间:2017-08-27 15:01:37

标签: json swift multidimensional-array swift3 nested

我正在尝试将从get请求收到的一些json数据转换为可用的数组或类似的东西

我收到的json数据看起来像这样

{
"elementlist":{

    "Ready Position":{

"Neutral Grip":["1,2,3,4,5"],"
Back Straight (Concave ir Convex?)":["1,2,3,4,5"],"
Body Low & Feet a little more than sholder width apart":["1,2,3,4,5"],"
Weight on Balls of Feet":["1,2,3,4,5"],"
Head Up":["1,2,3,4,5"],"
Sholder Blades Close":["1,2,3,4,5"],"
Eyes Drilled":["1,2,3,4,5"]
},

"Split Step":{"
Ready Position Conforms":["Yes,No"],"
Body Position Low":["1,2,3,4,5"],"
Legs Loaded/Prepared":["1,2,3,4,5"]
}
}
}

这是我正在使用的快捷方式

let playerAPIurl = "http://linkcoachuat.herokuapp.com/api/v1/session/element?organisation=5&group=green&sport=tennis"
var request = URLRequest(url: URL(string: playerAPIurl)!)
request.httpMethod = "GET"



let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

let task = session.dataTask(with: request) { (data, response, error) in
    if error != nil {
        print("ERROR")
    }
    else{


        do{

            print("hello")

            let myJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

          // Convert myJson into array here

           print(myJson)
                           }

        catch
        {
        }

    }}

我想要做的是获取嵌套数组的名称数组,以便元素阵列= ["准备好位置","分裂步骤"]然后是能够通过说myJson [elementarray [0]]或类似的东西来访问数组

我有点像一个快速的菜鸟,所以任何帮助,请尝试解释答案,以便他们很容易理解

感谢您的帮助

1 个答案:

答案 0 :(得分:3)

您可以尝试以与您已经制作的方式相同的方式转发json:

let myJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

//creating the new array of additional elements
let elementArray: [[String: Any]] = []

//making myJson parsing for additional items
if let readyPosition = myJson?["Ready Position"] as? [String: Any] {
     elementArray.append(readyPosition)
}

if let splitStep = myJson?["Split Step"] as? [String: Any] {
     elementArray.append(splitStep)
}

make print(elementArray)以确保所有内容都已正确解析。

老实说,我更喜欢使用对象(自定义类或结构)来存储值,并且能够创建相关的实例或值,但由你决定