0

这是我对特定 API 的 JSON 响应。

情况1

  ChallengeConfiguration =     {
            AnswerAttemptsAllowed = 0;
            ApplicantChallengeId = 872934636;
            ApplicantId = 30320480;
            CorrectAnswersNeeded = 0;

            MultiChoiceQuestion =         (
               {
    FullQuestionText = "From the following list, select one of your current or previous employers.";
    QuestionId = 35666244;
    SequenceNumber = 1;
                },
                {
    FullQuestionText = "What color is/was your 2010 Pontiac Grand Prix?";
    QuestionId = 35666246;
    SequenceNumber = 2;
                }
                                           )

    }

键“MultiChoiceQuestion”返回一个包含两个问题的数组。所以这是我的代码。

let QuestionArray:NSArray = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as! NSArray

案例2

  ChallengeConfiguration =    

                            {

                AnswerAttemptsAllowed = 0;
                ApplicantChallengeId = 872934636;
                ApplicantId = 30320480;
                CorrectAnswersNeeded = 0;

                MultiChoiceQuestion =         {

        FullQuestionText = "From the following list, select one of your 
 current or previous employers.";

       QuestionId = 35666244;
       SequenceNumber = 1;
                                              }

                                   }

对于案例 2,我的代码不起作用并且应用程序崩溃,因为它返回该特定键的字典。那么我怎样才能编写一个适用于所有对象的通用代码呢?

4

1 回答 1

0

看起来键可以包含字典值数组或字典,因此您只需要尝试强制转换即可查看您拥有哪个。

所以我可能会这样做:

if let arr = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as? Array {
    // parse multiple items as an array
} else if let arr = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as? [String:AnyObject] {
   // parse single item from dictionary
}

你永远不应该真正使用!强制展开某些东西,除非您完全确定该值存在并且是您期望的类型。

在此处使用条件逻辑来测试响应并安全地解析它,这样您的应用即使在失败时也不会崩溃。

于 2017-04-30T19:39:32.033 回答