Swift 4 Json 解析

埃姆雷·卡坎

我需要将这个 json 数据扔到上面的“arrayCategory”数组中。我该怎么做 ?

“Elektronik”和“Hobi”的标题不是固定的。它是可变的。

JSON 数据

{
  "Elektronik": [
    {
      "kategoriisim": "Akıllı Saatler",
      "uyevarmi": "1"
    },
    {
      "kategoriisim": "Anakart",
      "uyevarmi": "1"
    } ],

  "Hobi": [
    {
      "kategoriisim": "Drone Multikopter",
      "uyevarmi": "1"
    }
  ]
}
  • 结构体和数组。我需要填写“DimensionArray”数组

ExpandableNames "baslik" = json 数据中 "Elektronik" 数据的未来

ExpandableNames "kategori" = "Elektronik" 电路的子元素将出现

    struct ExpandableNames {

        let baslik : String
        let kategori: [cellKategorilerData]
    }
    struct cellKategorilerData {
        var kategoriisim : String?
        var uyevarmi : String?
    }

    var dimensionalArray = [ExpandableNames]()
    var arrayKategoriData = [cellKategorilerData]()

——

static func jsonSonucGetir(servlet:String,parametre:String) {

        let connectString = Connect.ConnectInfo

        var request = URLRequest(url: URL(string:connectString.conString + "/" + servlet)!)
        request.httpMethod = "POST"

        var postString = parametre
        postString = postString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            if error != nil
            {
                print("error" , error)

            }

            if let urlContent = data
            {
                do
                {
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject



                       ???

                }
                catch
                {
                    print("server hatasi")

                }
            }
        }

        task.resume()
    }
瓦迪安

如果键是动态的,我建议将对象解码为字典 ( [String:[CellKategorilerData]])

let jsonString = """
{
    "Elektronik": [
        {"kategoriisim": "Akıllı Saatler", "uyevarmi": "1"},
        {"kategoriisim": "Anakart", "uyevarmi": "1"}
    ],
    "Hobi": [
        {"kategoriisim": "Drone Multikopter", "uyevarmi": "1"}
    ]
}
"""

struct CellKategorilerData : Decodable {
    let kategoriisim : String
    let uyevarmi : String
}

do {
    let data = Data(jsonString.utf8) 
    let result = try JSONDecoder().decode([String:[CellKategorilerData]].self, from: data)
    for (key, value) in result {
        print("key", key, "value", value)
    }
} catch { print(error) }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章