简体   繁体   中英

IOS/Swift/JSON: Parse nested JSON with swiftyJSON

I am having trouble parsing the following nested JSON. I can get the first level but not subsequent levels. Can anyone suggest right syntax to get "anger"? Thanks in advance for any suggestions.

JSON:

{
    "document_tone" =     {
        "tone_categories" =         (
                        {
                "category_id" = "emotion_tone";
                "category_name" = "Emotion Tone";
                tones =                 (
                                        {
                        score = "0.218727";
                        "tone_id" = anger;
                        "tone_name" = Anger;
                    },  
                );
            },
    );
} 

Code:

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
        }
    }
}

You can try

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"])
                    }
                 }
             }
      }
   }
}

To print Anger at 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
                        }
                    }
                }
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM