IOS/Swift/JSON:使用 swiftyJSON 解析嵌套的 JSON
Posted
技术标签:
【中文标题】IOS/Swift/JSON:使用 swiftyJSON 解析嵌套的 JSON【英文标题】:IOS/Swift/JSON: Parse nested JSON with swiftyJSON 【发布时间】:2018-06-01 22:54:07 【问题描述】:我在解析以下嵌套 JSON 时遇到问题。我可以获得第一级,但不能获得后续级别。任何人都可以建议正确的语法来获得“愤怒”吗?提前感谢您的任何建议。
JSON:
"document_tone" =
"tone_categories" = (
"category_id" = "emotion_tone";
"category_name" = "Emotion Tone";
tones = (
score = "0.218727";
"tone_id" = anger;
"tone_name" = Anger;
,
);
,
);
代码:
if let result = response.result.value as? [String:Any]
if let tone = result["document_tone"] as? [String:Any]
print(tone) //This prints ok
if let cat = tone["tone_categories"] as? String
print("here is%@",cat)//prints as null
【问题讨论】:
显然“tone_categories”是字典数组,而不是字符串。 【参考方案1】:在tone_name
打印愤怒
if let result = response.result.value as? [String:Any]
if let tone = result["document_tone"] as? [String:Any]
if let cat = tone["tone_categories"] as? [[string:Any]]
if let dic = cat[0] as? [string:Any]
if let tones = dic ["tones"] as? [[String:Any]]
if let toneDic = tones[0] as? [string:Any]
print(toneDic["tone_name"]) //print Anger
【讨论】:
【参考方案2】:你可以试试
if let result = response.result.value as? [String:Any]
if let tone = result["document_tone"] as? [String:Any]
print(tone)
if let cat = tone["tone_categories"] as? [[String:Any]]
if let dic = cat[0] as? [String:Any]
if let catId = dic["category_id"] as? String
print("catId is %@",catId)
if let catName = dic["category_name"] as? String
print("catName is %@",catName )
if let alltones = dic["tones"] as? [[String:Any]]
print("alltones is %@",alltones)
if let innerTone = alltones[0] as? [String:Any]
print(innerTone["tone_name"])
print(innerTone["tone_id"])
【讨论】:
以上是关于IOS/Swift/JSON:使用 swiftyJSON 解析嵌套的 JSON的主要内容,如果未能解决你的问题,请参考以下文章