2017-02-16 11 views
0

タイトルが不明な場合はお詫び申し上げます。私はNSDictionaryとJSONがどのくらい正確に機能しているかについてはあまりよく分かりません。NSDictionaryで辞書内にネストされた値を取得する方法は?

私は、.JSONファイルから値を取り出し、コンソールに出力するSwiftを使って簡単なアプリケーションを作成しようとしています。ここにJSONファイルがあります:

{ 

"students": [ 
    { 
     "name": "Stew Dent", 
     "age": "10", 
     "year": 6, 
     "grades": [ 
      { 
       "english": "a-plus", 
       "math": "b-plus" 
      }, 
      { 
       "english": "a", 
       "math": "a-minus" 
      } 
     ] 

    }, 

    { 
     "name": "Mary Brown", 
     "age": "14", 
     "year": 10, 
     "grades": [ 
      { 
       "english": "a-plus", 
       "math": "a-plus" 
      }, 
      { 
       "english": "a-plus", 
       "math": "a" 
      } 
     ] 

    } 
] 

} 

現在、「グレード」の値を除くすべての値を取得できます。ここに私のスウィフトコードは次のとおりです。

if let path = Bundle.main.path(forResource: "school", ofType: "json") 
    { 
     do { 
      // Retrieve data from JSON file 
      let jsonData = try NSData(contentsOfFile: path, options: .mappedIfSafe) 

      // Convert data into NSDictionary 
      let jsonResult = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary 



      if let students : [NSDictionary] = jsonResult?["students"] as? [NSDictionary] 
      { 
       if let grades : [NSDictionary] = students["grades"] as? [NSDictionary] 
       { 
        for grade: NSDictionary in grades 
        { 
         for (subject, gradevalue) in grade 
         { 
          print ("\(subject): \(gradevalue)") 
         } 

        } 
       } 



      } 



     } catch 
     { 

     } 


    } 

私は間違っていないよ場合は、「等級」は「学生」の辞書内の辞書です。ただし、上記のコードを実行できません。 "if let grades ..."行には、 "インデックスタイプが 'String'の添字 '[NSDictionary]'の値を添削することはできません。

私は間違っています?これらの値を取得するためにどのような方法でもありますか?私は何かが足りないのですか?任意の助けいただければ幸いです。おかげで:)

+0

なぜSwift辞書の代わりにNSDictionaryを使用していますか?それについては – rmaddy

+0

@rmaddy idk。私がSwiftを学ぶのに使った本はもともとそれを使っていたので、それが私が学んだものです。スウィフト辞書を使う方が良いですか?違いはなんですか? –

答えて

1

をあなたはスウィフトネイティブ型Dataの代わりに、NSDataと辞書[String:Any]の代わりNSDictionaryを使用する必要があります。また、忘れてしまいました各生徒の繰り返しを試してみてください。

do { 
    if let dict = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any] { 
     print(dict) 
     if let students = dict["students"] as? [[String: Any]] { 
      print(students) 
      for student in students { 
       print(student["name"] ?? "") 
       if let grades = student["grades"] as? [[String: Any]] { 
        for grade in grades { 
         for (subject, gradevalue) in grade { 
          print ("student:",student["name"] ?? "", "subject:", subject, "grade:", gradevalue) 
         } 
        } 
       } 
      } 
     } 
    } 
} catch { 
    print(error) 
} 
+1

うわー、ありがとう!これは完全に機能しました!また、NSDataの代わりにjsonData = NSData(contentsOfFile:path、options:.mappedIfSafe)を試してみましょう。 –

0

このコードを試してみてください。これはあなたがしようとしているものを見てください。

  if let path = Bundle.main.path(forResource: "student", ofType: "json") 
    { 
     do { 
      // Retrieve data from JSON file 
      let jsonData = try NSData(contentsOfFile: path, options: .mappedIfSafe) 

      // Convert data into NSDictionary 
      let jsonResult = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary 



      if let students = jsonResult?["students"] as? [NSDictionary] 
      { 
       for student in students 
       { 
        for grades in student["grades"] as! [[String:String]]{ 
         for eachGrade in grades{ 
          print("\(eachGrade.key) : \(eachGrade.value)") 
         } 

        } 
       } 
      } 
     } 
     catch 
     { 

     } 

} 
関連する問題