【发布时间】:2018-03-19 15:15:42
【问题描述】:
我无法解析 JSON 数据中的 JSON 数组,因为我收到的 JSON 数组并不总是数组。
数组的键是Body,取决于另一个名为infoType 的参数。 Body 将是一个数组或字符串。 infoType's的值可以是1、2、3或4。当收到infoType == 4时,我们得到Body作为一个数组,当infoType的值等于1、2或3时,我们收到Body 作为普通字符串。
当我收到Body 作为JSON 数组时,我想对其进行解析,当它是普通字符串时,我希望将其保存为普通字符串。
这是我的代码:
import Foundation
import UIKit
var Parsedinfo = [InfoClass]()
class UserInfo: UIViewController
{
func parseData()
{
Parsedinfo = []
let url : String = "url"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if let data = data
{
do
{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! NSArray
for Info in json
{
let info = Info as! [String:Any]
let Title = info["Title"]
let InfoID = info["InfoID"]
let infoType = info["infoType"]
let Body = info["Body"]
Parsedinfo.append(InfoClass(Title : Title as! String, Body: Body as!String,infoType : infoType as! Int, InfoID : InfoID as! Int))
}
}
catch
{
print (error)
}
}
}
task.resume()
}
}
class InfoClass
{
var Title : String
var Body : String
var InfoID : Int
var infoType : Int
init(Title : String,Body:String,infoType : Int, InfoID : Int)
{
self.Title = Title
self.Body = Body
self.InfoID = InfoID
self.infoType = infoType
}
}
这是Body 在infoType == 4 时的样子:
{"lat":000.00000,"lng":000.0000000,"desc":"string"}
当infoType is 1, 2, or 3, it's just a normal string like this:
"String"`
JSON 结构:
(
{
Body = "{"lat":00.0000,"lng":00.0000,"desc":"string"}";
InfoID = 139;
Title = "title";
UserID = "userid";
infoType = 4;
},
{
Body = " {"lat":00.0000,"lng":00.0000,"desc":"string"}";
InfoID = 340;
Title = yyy;
UserID = "userid";
infoType = 4;
},
{
Body = "Body";
InfoID = 340;
Title = yyy;
UserID = "userid";
infoType = 1;
}
)
【问题讨论】:
-
请添加您的 json 结构。
-
不相关,但 GET 请求不需要
URLRequest。这是默认设置。只需将url传递给数据任务,dataTask(with:也接受一个 URL。并且不要在 Swift 中使用NSArray / NSDictionary。你扔掉了强类型信息。使用原生集合类型。 -
@dahiya_boy 你去吧,我用你问的内容编辑了这个问题。