我需要使用Swift解析json的帮助。我无法使用swift将它们解析为类对象的数组。我尝试的是将json键值绑定到一个对象数组中并返回。但是,我无法处理这些类型。如此令人困惑。
有人可以帮我吗?
我拥有的json:
{
"mass_info1":
[{
"mass_id":7780,
"mass_date":"5/1/2019",
"mass_time":"7:30 PM",
"mass_location":"",
"mass_description": “Blah1”
} ] ,
"mass_info2":
[ {
"mass_id":7781,
"mass_date":"6/10/2019",
"mass_time":"7:30 PM",
"mass_location”:”1234 some place Los Angeles”,
"mass_description": “blah2”
} ] ,
"mass_info3":
[ {
"mass_id":7783,
"mass_date":"5/21/2019",
"mass_time":"7:30 PM",
"mass_location":"",
"mass_description": “blah3”
} ] ,
"mass_info4":
[ {
"mass_id":1115,
"mass_date":"4/5/2019",
"mass_time":"2:30 PM",
"mass_location":"4050 Mission Ave, Oceanside, CA 92057",
"mass_description": “blah4”
} ]
}
MassInfoObject类导入Foundation
struct MassInfoObject {
var mass_id:Int
var mass_date: String?
var mass_time:String?
var mass_location:String?
var mass_description:String?
init(mass_id:Int,mass_date:String,
mass_time:String,mass_location:String,mass_description:String)
{
self.mass_id=mass_id
self.mass_date=mass_date
self.mass_time=mass_time
self.mass_location=mass_location
self.mass_description=mass_description
}
}
和我从URLSession中获取json的代码。
func getjson()->[MassInfoObject]? {
let urlPath = "http://myclassinfo.com/dev/json.php"
let url = URL(string: urlPath)
var massObjArray = [MassInfoObject]()
var index:Int = 0
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
print("Task completed")
guard data != nil && error == nil else {
//print(error?.localizedDescription)
return
}
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
for (key, value) in jsonResult {
//print("Value: \(value) for key: \(key)")
if let results = jsonResult[key] as? [String]
{
let dict = results[index].toJSON() as? [String:AnyObject] // can be any type here
for (key,value) in dict!{
let result2 = dict![key] as! String
print (result2)
}
}
}
}
} catch let parseError as NSError {
print("JSON Error \(parseError.localizedDescription)")
}
}
task.resume()
return massObjArray
}
答案 0 :(得分:0)
您要解析的json没有非常合理的结构。如果您可以控制json,则应先进行处理。如果您没有控制权,建议您在解析之前在客户端上转换json。
以下在游乐场中起作用:
let str = """
{ "mass_info1": [{ "mass_id":7780, "mass_date":"5/1/2019", "mass_time":"7:30 PM", "mass_location":"", "mass_description": "Blah1"
} ] ,
"mass_info2": [ { "mass_id":7781, "mass_date":"6/10/2019", "mass_time":"7:30 PM", "mass_location":"1234 some place Los Angeles", "mass_description": "Blah2"
} ] ,
"mass_info3":
[ { "mass_id":7783, "mass_date":"5/21/2019", "mass_time":"7:30 PM", "mass_location":"", "mass_description": "blah3"
} ] ,
"mass_info4":
[ { "mass_id":1115, "mass_date":"4/5/2019", "mass_time":"2:30 PM", "mass_location":"4050 Mission Ave, Oceanside, CA 92057", "mass_description": "blah4"
} ]
}
"""
struct MassInfoObject: Codable {
var mass_id: Int
var mass_date: String?
var mass_time: String?
var mass_location: String?
var mass_description: String?
}
let data = str.data(using: .utf8)!
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: [[String: Any]]]
let jsonArray = json!.values.map { $0 }
let cleanedJson = try JSONSerialization.data(withJSONObject: jsonArray, options: [])
let decoder = JSONDecoder()
let items = try decoder.decode([[MassInfoObject]].self, from: cleanedJson)
第一步是将json转换为易于解析的内容。由于现在MassInfoObject符合Codable
,因此您可以使用简单的JSONDecoder解码对象数组,这只是一行代码。
此外,在您的网络代码中,您正在调用异步任务,但是您将立即返回,这是行不通的。从getJson
函数返回时,您还没有结果。最简单的方法是使用闭包,您可以在闭包中调用结果:
在您的网络代码中,它看起来像这样:
func getjson(handler: @escaping ([MassInfoObject]?)->()) {
let urlPath = "http://myclassinfo.com/dev/json.php"
let url = URL(string: urlPath)
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
print("Task completed")
guard let data = data && error == nil else {
//print(error?.localizedDescription)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: [[String: Any]]]
let jsonArray = json!.values.map { $0 }
let cleanedJson = try JSONSerialization.data(withJSONObject: jsonArray, options: [])
let decoder = JSONDecoder()
let items = try decoder.decode([[MassInfoObject]].self, from: cleanedJson).compactMap { $0 }
handler(items)
} catch let parseError as NSError {
print("JSON Error \(parseError.localizedDescription)")
handler(nil)
}
}
task.resume()
}
如果您的json如下所示:
[
{
"mass_description": "Blah1",
"mass_date": "5/1/2019",
"mass_location": "",
"mass_time": "7:30 PM",
"mass_id": 7780
},
{
"mass_description": "blah2",
"mass_date": "6/10/2019",
"mass_location": "1234 some place Los Angeles",
"mass_time": "7:30 PM",
"mass_id": 7781
},
{
"mass_description": "blah3",
"mass_date": "5/21/2019",
"mass_location": "",
"mass_time": "7:30 PM",
"mass_id": 7783
},
{
"mass_description": "blah4",
"mass_date": "4/5/2019",
"mass_location": "4050 Mission Ave, Oceanside, CA 92057",
"mass_time": "2:30 PM",
"mass_id": 1115
}
]
您可以轻松地对此进行解码:
let items = try JSONDecoder().decode([MassInfoObject].self, data)
答案 1 :(得分:0)
感谢Marcel,以及所有帮助我的人。这是我使用的代码
struct MassObj:Decodable{
var mass_id:Int
var mass_date: String
var mass_time:String
var mass_location:String
var mass_description:String
}
func getJsonArray2() {
let urlPath = "http://myclassinfo.com/dev/json.php"
guard let url = URL(string: urlPath) else {return }
let task = URLSession.shared.dataTask(with: url)
{
data, response, error in
print("Task completed")
guard data != nil && error == nil else {
//print(error?.localizedDescription)
return
}
do{
var massArray = [MassObj]()
massArray = try JSONDecoder().decode([MassObj].self, from:data!)
for object in massArray {
print("\(object.mass_id) == \(object.mass_date) == \(object.mass_description)")
}
}catch let jerr {
print(jerr)
}
}
task.resume()
}
================= 而json是
[
{
"mass_description": "Blah1",
"mass_date": "5/1/2019",
"mass_location": "",
"mass_time": "7:30 PM",
"mass_id": 7780
},
{
"mass_description": "blah2",
"mass_date": "6/10/2019",
"mass_location": "1234 some place Los Angeles",
"mass_time": "7:30 PM",
"mass_id": 7781
},
{
"mass_description": "blah3",
"mass_date": "5/21/2019",
"mass_location": "",
"mass_time": "7:30 PM",
"mass_id": 7783
},
{
"mass_description": "blah4",
"mass_date": "4/5/2019",
"mass_location": "4050 Mission Ave, Oceanside, CA 92057",
"mass_time": "2:30 PM",
"mass_id": 1115
}
]