我从PHP API获得了这个json数据。但如何将其转换为在应用程序中显示。实际上它在添加圈子名称和id之前工作正常但是当这个api返回圈子名称时它不起作用。请帮忙。提前致谢。
JSON:["data": <__NSArrayM 0x60800025bed0>(
{
Email = "ganesh@gmail.com";
ID = 104;
Name = archana;
Phone = "( 91)9111111110";
status = 1;
timeinterval = 15;
userpic = "";
},
{
circleName = "<null>";
circleid = 155;
}
)
]
下面是我的代码。
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String:Any]
print("JSON:\(json)")
if let data = json["data"] as? [[String:String]]
{
self.stopIndicator()
print("DATA:\(data)")
if let errorString = data.first?["Error"]
{
print("Error: \(errorString)")
if (errorString == "Invalid Email or Password")
{
// Perform Operation in Main thread
OperationQueue.main.addOperation
{
let alertController = UIAlertController(title: "Invalid Email or Password", message: "Your Email or password is Invalid. Please Enter Correct Email or Pasword.", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {(_action) -> Void in
_ = self.navigationController?.popViewController(animated: false)
}))
self.present(alertController, animated: true, completion: nil)
}
}
}
else if let UserArray = (json as AnyObject).object(forKey: "data") as? NSArray
{
for UserDic in UserArray
{
var Email:String
var ID:String
var Name:String
var Phone:String
var status:String
var timeinterval:String
var userpic:String
Email = ((UserDic as AnyObject).object(forKey: "Email") as? String)!
ID = ((UserDic as AnyObject).object(forKey: "ID") as? String)!
Name = ((UserDic as AnyObject).object(forKey: "Name") as? String)!
Phone = ((UserDic as AnyObject).object(forKey: "Phone") as? String)!
status = ((UserDic as AnyObject).object(forKey: "status") as? String)!
timeinterval = ((UserDic as AnyObject).object(forKey: "timeinterval") as? String)!
userpic = ((UserDic as AnyObject).object(forKey: "userpic") as? String)!
let userModel = UserDetailsArray(UserEmail: Email, UserId: ID, UserName: Name, UserPhone: Phone, UserStatus: status, TimeInterVal: timeinterval, UserPic: userpic)
答案 0 :(得分:1)
你有一个字典数组,每个字典在解析时都有不同的结构。
我为什么这么说?
json = [dictionaryOne, dictionaryTwo...]
dictionaryOne = ["Email": "" , "ID": ....]
dictionaryTwo = ["cicileName": nil, "circleid": ""....]
现在,在解析数组时,
for UserDic in UserArray {
// here initialising the variables
}
您没有确定第二个结构字典会出现,这就是您收到错误的原因。
简单的解决方案是进行检查,即
for UserDic in UserArray {
if let circleName = (UserDic as AnyObject).object(forKey: "circleid") as? String {
// do not parse if you don't need the data of this dict and continue
continue;
} else {
// parse the other dictionary which has Email, ID etc
var Email: String
var ID:String
.
.
.
}
}
如果你想存储两个字典,那么定义类似的变量并存储在if块中。