JSON не разбирается должным образом - PullRequest
0 голосов
/ 08 января 2019

Итак, я попытался проанализировать файл json, и когда я анализирую его в соответствии с синтаксисом, он выдает ошибку, которая не может изменить строку на массив словаря, но когда я исправляю проблему, он генерирует nil. Может ли кто-нибудь высказать свое мнение

func jsonFour() {
    let string = "[{\"address\": 7023000630,\"reportStatus\": \"Retrieved\",\"currentLocation\": {\"latitude\": 29.8529, \"longitude\": 73.99332,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\"} }, {\"address\": 7290098339, \"reportStatus\": \"Retrieved\", \"currentLocation\": {\"latitude\": 21.628569, \"longitude\": 72.996956,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\" } } ]"

    let data = string.data(using: .utf8)!
    do {
        if let jsonArray = try JSONSerialization.jsonObject(with: data, options : JSONSerialization.ReadingOptions.mutableContainers) as? [[ String : Any ]]
        {
            print(jsonArray) // use the json here
            let address = jsonArray["address"] as! [[String:Any]]
            if let timestamp = address["timestamp"] as? [String]{print(timestamp)}
        } else {
            print("bad json")
        }
    } catch let error as NSError {
        print(error)
    }

}

Когда я удаляю двойные скобки из "String : Any", он работает нормально, но не дает никакого значения, кроме nil.

И когда я продолжаю в том же духе, он пропускает оператор if и просто печатает "bad json".

Что я здесь не так делаю?

Ответы [ 4 ]

0 голосов
/ 08 января 2019

В вашем фрагменте кода jsonArray является array, а массив не может содержать значение типа [[String: Any]], поэтому вместо этого вы должны выполнить синтаксический анализ, например,

func jsonFour(){
    let string = "[{\"address\": 7023000630,\"reportStatus\": \"Retrieved\",\"currentLocation\": {\"latitude\": 29.8529, \"longitude\": 73.99332,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\"} }, {\"address\": 7290098339, \"reportStatus\": \"Retrieved\", \"currentLocation\": {\"latitude\": 21.628569, \"longitude\": 72.996956,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\" }}]"

    let data = string.data(using: .utf8)!
    do {
        if let jsonArray = try JSONSerialization.jsonObject(with: data, options : JSONSerialization.ReadingOptions.mutableContainers) as? [[String: Any]]
        {
            print(jsonArray) // print the json here
            for jsonObj in jsonArray {
                if let dict = jsonObj as? [String: Any] {
                    if let address = dict["address"] {
                        print(address)
                    }
                    if let location = dict["currentLocation"] as? [String: Any], let timeStamp = location["timestamp"]  {
                        print(timeStamp)
                    }
                }
            }
        } else {
            print("bad json")
        }
    } catch let error as NSError {
        print(error)
    }
}
0 голосов
/ 08 января 2019

Конечно, вы должны использовать Codable для этого, но для запуска кода используйте

let string = "[{\"address\": 7023000630,\"reportStatus\": \"Retrieved\",\"currentLocation\": {\"latitude\": 29.8529, \"longitude\": 73.99332,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\"} }, {\"address\": 7290098339, \"reportStatus\": \"Retrieved\", \"currentLocation\": {\"latitude\": 21.628569, \"longitude\": 72.996956,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\" } } ]"

let data = string.data(using: .utf8)!

do {
    if let jsonArray = try JSONSerialization.jsonObject(with: data) as? [[ String : Any ]]
    {
        jsonArray.forEach {

            if  let add = $0["address"] as? Int  , let currentLocation = $0["currentLocation"] as? [String:Any], let timestamp = currentLocation["timestamp"] as? String
            {
                print("address is : ", add ,"timestamp is : " , timestamp)
            }
        }

    } else {
        print("bad json")
    }
} catch  {
    print(error)
}

Ваша очевидная проблема здесь

let address = jsonArray["address"] as! [[String:Any]]

jsonArray - это массив, который вы не можете подписать с помощью ["address"]

0 голосов
/ 08 января 2019

Массив - это список. Он может содержать несколько элементов. Вы должны использовать цикл для итерации массива (как в вашем предыдущем вопросе )

  • Значение ключа address равно Int (без двойных кавычек).
  • Значение ключа timestamp равно String и находится в словаре для ключа currentLocation в массиве

    let data = Data(string.utf8)
    do {
        if let jsonArray = try JSONSerialization.jsonObject(with: data) as? [[String : Any]]
        {
            print(jsonArray) // use the json here
            for item in array {
               let address = item["address"] as! Int
               let currentLocation = item["currentLocation"] as! [String:Any]
               let timestamp = currentLocation["timestamp"] as! String
               print(timestamp)
            }
        } else {
            print("bad json")
        }
    } catch {
        print(error)
    }
    

Никогда не используйте .mutableContainers в Swift. Это бессмысленно.

0 голосов
/ 08 января 2019

Поскольку существует Codable, я настоятельно рекомендую вам использовать его вместо JSONSerialization.

Итак, начните с объявления ваших структур, совпадающих с вашей структурой JSON

struct Model: Codable {
    var address: Int
    var reportStatus: String
    var currentLocation: Location
}

struct Location: Codable {
    var latitude, longitude: Double
    var timestamp: String
}

Теперь просто декодируйте ваш JSON, используя JSONDecoder

do {
    let data = string.data(using: .utf8)!
    let models = try JSONDecoder().decode([Model].self, from: data)
} catch {
    print(error)
}

... сейчас models - это массив Model объектов, и вы можете работать с ним.

...