如何解析本地文件中的json数据? [英] how to parse json data from local files?

查看:94
本文介绍了如何解析本地文件中的json数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对json解析非常陌生,并尝试解析具有汽车列表的json文件,但是当我解析时,它给出了nil

i am very new to json parsing and tried to parse a json file which has list of cars but when i do parse, it gives out nil

    func jsonTwo(){
    let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
    let data = try! Data(contentsOf: url)
    let JSON = try! JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
    print(".........." , JSON , ".......")
    let brand = JSON?["models"] as? [[String : Any]]
    print("=======",brand,"=======")
}

以及当我对下面的代码进行如下修改

and when i made some modifications to this code as below

    func jsonTwo(){
    let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
    let data = try! Data(contentsOf: url)
    let JSON = try! JSONSerialization.jsonObject(with: data, options: []) 
    print(".........." , JSON , ".......")
    let brand = JSON["brand"] as? [[String : Any]]
    print("=======",brand,"=======")
}

然后我得到并错误提示"Type'Any'没有下标成员"

then i get and error saying "Type 'Any' has no subscript members"

下面是我正在使用的json文件的示例

below is a sample of the json file that i am using

[{"brand": "Aston Martin", "models": ["DB11","Rapide","Vanquish","Vantage"]}]

推荐答案

请注意,代码中的变量JSON是对象数组. 您必须正确地投射它.

Please note that variable JSON in your code is an array of objects. You have to cast it properly.

func jsonTwo(){
    let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
    let data = try! Data(contentsOf: url)
    let JSON = try! JSONSerialization.jsonObject(with: data, options: []) 
    print(".........." , JSON , ".......")
    if let jsonArray = JSON as? [[String: Any]] {
        for item in jsonArray {
            let brand = item["brand"] as? String ?? "No Brand" //A default value
            print("=======",brand,"=======")
        }
    }
}

这篇关于如何解析本地文件中的json数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆