如何从alamofire响应中获取字典数组的值?

问题描述 投票:0回答:1

我正在尝试使用Alamofire和swift从json响应中提取“ArticleID”和“Title”。

[
"MetaTitle": <null>, "IsFeatured": 1, "EndDate": <null>, "LastUpdateID": 8684, 
"DnnForge_NewsArticles_Page": <__NSSingleObjectArrayI 0x6080000109b0>(
{
ArticleID = 4649;
PageID = 4649;
PageText = "&lt;a href=&quot;/kshnezam/Portals/0/Users/236/84/8684/\U0628\U0648\U062f\U062c\U0647 97.zip&quot;&gt;\U0628\U0648\U062f\U062c\U0647 97.zip&lt;/a&gt;";
SortOrder = 0;
Title = "\U0628\U0648\U062f\U062c\U0647 \U067e\U06cc\U0634\U0646\U0647\U0627\U062f\U06cc \U0633\U0627\U0644 97 \U0633\U0627\U0632\U0645\U0627\U0646";
}
)
, "IsApproved": 1, "PageHeadText": <null>, "FileCount": 0, "RatingCount": 0, 
"Title": بودجه پیشنهادی سال 97 سازمان, "RssGuid": <null>, "CommentCount": 
    0, "IsNewWindow": 0, "CreatedDate": 2018-01-25T13:17:04.493,
"LastUpdate": 2018-01-25T13:17:22.87, 
"ArticleID": 4649, "MetaKeywords": <null>, "AuthorID": 8684, "ShortUrl": <null>, "ModuleID": 422, "StartDate": 2018-01-24T13:14:00, "ImageUrl": <null>, "MetaDescription": <null>, "PageCount": 1, 
"DnnForge_NewsArticles_ArticleCategories": <__NSSingleObjectArrayI 0x6080000114f0>(
{
ArticleID = 4649;
CategoryID = 2;
}
)
]

我是新手,我无法找到实现这一目标的方法。如何获取“ArticleID”和“Title”的值?

Alamofire.request("https://example.com/getNews").responseJSON { response in

    }
json swift alamofire
1个回答
0
投票

你需要这样的东西:

Alamofire.request("https://example.com/getNews").responseJSON { response in

    switch response.result {

    case .success(let result):

        let resultsArray = result as! [AnyObject]
        let resultDic = resultsArray[0] as! [String: Any] // I'm using just the first one.
        let articleID = resultDic["ArticleID"] as! Int // (I assume) 
        let title = resultDic["Title"] as! String

       // I'm just creating the let with the values, from here depends on your implementation. 

    default:
        print("Error")
    }
}

确保响应中的字段不为空,在这种情况下,强制解包会使应用程序崩溃。

© www.soinside.com 2019 - 2024. All rights reserved.