我有以下JSON文件
{
"events": [
{
"date": "01/11/2017",
"name": [
"Tulsi Vivah",
"Pradosh Vrat"
],
"photo": [
"photo_chaturthi",
"photo_ekadashi"
]
},
{
"date": "03/11/2017",
"name": [
"Guru Nanak Jayanti"
],
"photo": [
"photo_chaturthi",
"photo_ekadashi"
]
}
]
}
我想解析这个并将objectArray中的元素放在下面的代码中:
struct Objects {
var sectionName : String!
var sectionObjects : [String]!
var sectionImages : [String]!
}
var objectArray = [Objects]()
我写了以下代码来阅读文件:
if let file = Bundle.main.url(forResource: "EventsEnglish112017", withExtension: "json") {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data as Data, options: [])
我的问题是如何进行类型转换" json"阅读单个元素以填充上述objectArray
。
谢谢!
答案 0 :(得分:1)
JSON是[String:Any?]
类型的字典
解析它:
if let dictionary = json as? [String: Any?] {
if let events = dictionary["events"] as? [[String: Any?]] {
// events is an array of JSON objects, so it's an array of dictionaries
for item in events
{
let date = item["date"] as? String // this is a String?
let name = item["name"] as? [String]
// same goes for 'photo'
}
}
}
现在您已检索到数据,您可以使用它来构建自定义对象。 但是如果你使用一些可以为你制作它的库,或者使用Swift4
,那就更好了答案 1 :(得分:-1)
从JSON文件中检索数据
(Swift 3)
if let path = NSBundle.mainBundle().pathForResource("myJson", ofType: "json")
{
if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
{
if let jsonResult = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? [String: Any]
{
if let eventsInfo = jsonResult["events"] as? [Any]
{
// Here you will get your data in Array format.
// for e.g
// print(eventsInfo[0]["date"])
// Just pass this eventsInfo (Array) into you Object model initializer and parse with the keys there.
}
}
}
}
(Swift 4)
if let path = Bundle.main.path(forResource: "myJson", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let eventsInfo = jsonResult["events"] as? [Any] {
// Here you will get your data in Array format.
// for e.g
// print(eventsInfo[0]["date"])
// Just pass this eventsInfo (Array) into you Object model initializer and parse with the keys there.
}
} catch {
// handle error
}
}