Ios 如何使用数组和更多JSON来解码JSON?

Ios 如何使用数组和更多JSON来解码JSON?,ios,json,swift,parsing,codable,Ios,Json,Swift,Parsing,Codable,我最近开始学习斯威夫特。我需要解码下面的json JSON中还有两个JSON,第一个(验证)不重要。第二个(结果)内部有一个JSON数组(serviceCenter)。我需要每个服务中心的信息。我尝试使用servicecenter作为可解码类来获取servicecenter对象,但由于JSON没有正确的格式,我无法这样做 [ { "validation": { "bValid": true, "sDescription": "Access true."

我最近开始学习斯威夫特。我需要解码下面的json

JSON中还有两个JSON,第一个(验证)不重要。第二个(结果)内部有一个JSON数组(serviceCenter)。我需要每个服务中心的信息。我尝试使用servicecenter作为可解码类来获取servicecenter对象,但由于JSON没有正确的格式,我无法这样做

[
  {
    "validation": {
      "bValid": true,
      "sDescription": "Access true."
    }
  },
  {
    "result": {
      "serviceCenter": [
        {
          "model": "Vanquish",
          "color": "Purple",
          "make": "Aston Martin",
          "sTag": "3666",
          "sVin": "6JDO2345",
          "sMiles": "3666",
          "bDamage": "1",
          "dDateTime": "04-17-2018 9:38 AM"
        },
        {
          "model": "F360",
          "color": "Red",
          "make": "Ferrari",
          "sTag": "0010",
          "sVin": "6JDO2347",
          "sMiles": "80000",
          "bDamage": "1",
          "dDateTime": "04-17-2018 9:25 AM"
        },
        {
          "model": "Vanquish",
          "color": "Purple",
          "make": "Aston Martin",
          "sTag": "0009",
          "sVin": "6JDO2345",
          "sMiles": "25000",
          "bDamage": "1",
          "dDateTime": "04-17-2018 9:23 AM"
        },
        {
          "model": "Vanquish",
          "color": "Purple",
          "make": "Aston Martin",
          "sTag": "0003",
          "sVin": "6JDO2345",
          "sMiles": "20000",
          "bDamage": "1",
          "dDateTime": "04-12-2018 10:37 AM"
        }
      ]
    }
  }
]
我试了这么多,但我做不到

这是我的密码,有人能帮我吗

do {
    let parseoDatos = try JSONSerialization.jsonObject(with: data!) as! [AnyObject]
    let h = type(of: parseoDatos )
    print("'\(parseoDatos)' of type '\(h)'")
    let contenido = parseoDatos[1]["result"]

    if let services = contenido!! as? Dictionary<String, Array<Any>> {               
        for (_,serviceArray) in services {
            for sc in serviceArray{
                let h = type(of: sc )
                print("'\(sc)' of type '\(h)'")                        
            }
        }
    }
} catch {
    print("json processing failed")
}
试试这个代码

enum ParsingError: Error {
    case wrongFormat(String)
}

do {
    let jsonObject = try JSONSerialization.jsonObject(with: data!)
    guard let array = jsonObject as? [Any] else {
        throw ParsingError.wrongFormat("wrong root object")
    }
    guard array.count == 2 else {
        throw ParsingError.wrongFormat("array count != 2")
    }
    guard let dict = array[1] as? [String: Any] else {
        throw ParsingError.wrongFormat("can't parse dict from array")
    }
    guard let serviceCenters = (dict["result"] as? [String: Any])?["serviceCenter"] else {
        throw ParsingError.wrongFormat("can't parse serviceCenters")
    }
    guard let serviceCentersArray = serviceCenters as? [[String : Any]] else {
        throw ParsingError.wrongFormat("serviceCenters is not an array")
    }

    print("\(type(of: serviceCentersArray))\n", serviceCentersArray)

} catch {
    print("json processing failed: \(error)")
}

您可以使用
Codable

Initial响应具有InitialElement的数组,
InitialElement
是带有
验证的结构,
结果
,结果可能为nil

别忘了在
URL

URLSession.shared.dataTask(with: url!) { (data, response, error) in

                     if  let initial =  try? JSONDecoder().decode([InitialElement].self, from: data){

                         // inital now have array of InitialElement and InitialElement is is struct with validation , result  , result may be nil


                        print(initial)
                        }
                    }.resume()
使用此数据模型:

import Foundation

struct InitialElement: Codable {
    let validation: Validation?
    let result: ResultData?
}

struct ResultData: Codable {
    let serviceCenter: [ServiceCenter]
}

struct ServiceCenter: Codable {
    let model, color, make, sTag: String
    let sVin, sMiles, bDamage, dDateTime: String
}

struct Validation: Codable {
    let bValid: Bool
    let sDescription: String
}


extension InitialElement {
    init(data: Data) throws {
        self = try JSONDecoder().decode(InitialElement.self, from: data)
    }
}

谢谢大家的回答,这是我在这里的第一个问题,我觉得所有的帮助都很棒。我终于可以解决这个问题了。也许不是最好的方法,但代码如下:

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
        if error != nil{
            print("error=\(String(describing: error))")
            return
        }
        do {

            let parseoDatos = try JSONSerialization.jsonObject(with: data!) as! [AnyObject]
            let h = type(of: parseoDatos )
            print("'\(parseoDatos)' of type '\(h)'")
            let contenido = parseoDatos[1]["result"]


            if let services = contenido!! as? Dictionary<String, Array<Any>> {
                for (_,serviceArray) in services {
                    for sc in serviceArray{
                        let h = type(of: sc )
                        print("'\(sc)' of type '\(h)'")
                        let valid = JSONSerialization.isValidJSONObject(sc) // true
                        print(valid)
                        do {
                            let jsonData = try JSONSerialization.data(withJSONObject: sc, options: .prettyPrinted)
                            let serviceDecoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
                            if let scJSON = serviceDecoded as? [String:String] {
                                print ("--------------------------")
                                print("'\(scJSON)' of type '\(type(of: scJSON))'")
                                print ("--------------------------")


                            }
                        } catch {
                            print(error.localizedDescription)
                        }
let task=URLSession.shared.dataTask(with:request){(data:data?,response:URLResponse?,error:error?)在
如果错误!=nil{
打印(“错误=\(字符串(描述:错误)))
返回
}
做{
让parseoDatos=尝试JSONSerialization.jsonObject(使用:data!)作为![AnyObject]
设h=类型(of:parseoDatos)
打印“\(h)”类型的(“\(parseoDatos)”
让contenido=parseoDatos[1][“结果”]
如果let services=contenido!!as?字典{
用于服务中的(\ u,serviceArray){
用于serviceArray中的sc{
设h=类型(of:sc)
打印“\(h)”类型的“\(sc”)
让valid=JSONSerialization.isValidJSONObject(sc)//true
打印(有效)
做{
让jsonData=try JSONSerialization.data(使用jsonObject:sc,选项:。预打印)
让serviceDecoded=尝试JSONSerialization.jsonObject(使用:jsonData,选项:[])
如果让scJSON=服务解码为?[String:String]{
打印(-----------------------------------)
打印“\(类型:scJSON))”类型的(“\(scJSON)”)
打印(-----------------------------------)
}
}抓住{
打印(错误。本地化描述)
}
我想稍后您会尝试按照建议使用Codable,但目前代码运行正常。再次感谢!

//试试这个,它正在运行
//try this it is working

let arrayMain=try?JSONSerialization.jsonObject(with:jsonData!,options:.mutableLeaves) as! Array<Any>


//print(arrayMain!)

if let firstDictionart=arrayMain![0] as? [String: Any] {
    if let insideFirstDict = firstDictionart["validation"] as? [String: Any]{
       print(insideFirstDict["bValid"]!)
         print( insideFirstDict["sDescription"]!)

    }

}
if let resultDictionary=arrayMain![1] as? [String: Any] {
    if let serviceDictionary = resultDictionary["result"] as? [String: Any] {
        for array in serviceDictionary["serviceCenter"] as! Array<Any>{
            if let infoDicti=array as? [String: Any]  {
                print( infoDicti["color"]!)
                print( infoDicti["make"]!)
                print(  infoDicti["color"]!)
                print( infoDicti["sTag"]!)
                print( infoDicti["sVin"]!)
                print( infoDicti["sMiles"]!)
                print( infoDicti["sVin"]!)
                print( infoDicti["model"]!)
                print( infoDicti["bDamage"]!)
                print( infoDicti["dDateTime"]!)         
            } 
        }
      }

    }
让arrayMain=try?JSONSerialization.jsonObject(带有:jsonData!,选项:.mutableLeaves)作为!数组 //打印(arrayMain!) 如果让firstDictionart=arrayMain![0]作为?[String:Any]{ 如果让InsideFirstDictionart=firstDictionart[“验证”]作为?[字符串:任意]{ 打印(InsideFirstAct[“bValid”]!) 打印(InsideFirstAct[“sDescription”]!) } } 如果让resultDictionary=arrayMain![1]作为?[String:Any]{ 如果让serviceDictionary=resultDictionary[“结果”]作为?[字符串:任意]{ 将serviceDictionary[“serviceCenter”]中的数组作为!数组{ 如果让infodict=array as?[字符串:Any]{ 打印(Infodict[“颜色”]!) 打印(infodict[“make”]!) 打印(Infodict[“颜色”]!) 打印(infodict[“sTag”]!) 打印(infodict[“sVin”]!) 打印(Infodict[“微笑”]!) 打印(infodict[“sVin”]!) 打印(InfoDict[“模型”]!) 打印(infodict[“bDamage”]!) 打印(infodict[“dDateTime”]!) } } } }
我想建议:你可以使用很棒的
SwiftJSON
。SwiftyJSON可以让你在Swift中轻松处理JSON数据。你的可解码类是什么?请给我看看你的代码。正如@Glenn所说,SwiftyJSON是一个很棒的工具。或者,你可以看看Swift的协议。
//try this it is working

let arrayMain=try?JSONSerialization.jsonObject(with:jsonData!,options:.mutableLeaves) as! Array<Any>


//print(arrayMain!)

if let firstDictionart=arrayMain![0] as? [String: Any] {
    if let insideFirstDict = firstDictionart["validation"] as? [String: Any]{
       print(insideFirstDict["bValid"]!)
         print( insideFirstDict["sDescription"]!)

    }

}
if let resultDictionary=arrayMain![1] as? [String: Any] {
    if let serviceDictionary = resultDictionary["result"] as? [String: Any] {
        for array in serviceDictionary["serviceCenter"] as! Array<Any>{
            if let infoDicti=array as? [String: Any]  {
                print( infoDicti["color"]!)
                print( infoDicti["make"]!)
                print(  infoDicti["color"]!)
                print( infoDicti["sTag"]!)
                print( infoDicti["sVin"]!)
                print( infoDicti["sMiles"]!)
                print( infoDicti["sVin"]!)
                print( infoDicti["model"]!)
                print( infoDicti["bDamage"]!)
                print( infoDicti["dDateTime"]!)         
            } 
        }
      }

    }