Swift 4 Json Parse

时间:2018-03-28 14:30:44

标签: json swift

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

  

“Elektronik”和“Hobi”游戏并未修复。它是可变的。

     

Json Data

{
  "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()
    }

1 个答案:

答案 0 :(得分:0)

如果键是动态的,我建议将对象解码为字典([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) }