やりたい事
jsonをapiのエンドポイントから取得する事はできました。
decodeを行いたいです。
調べたところ、取得したjsonを同じ形式で構造体を用意してそこに格納する様なのですが、構造体の用意の仕方が悪いのかエラーが出てしまいます。
どの様な構造体を用意すれば良いのか教えて頂けると有り難いです。
よろしくお願いします。
エラー
error:typeMismatch(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), CodingKeys(stringValue: "task", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected to decode Int but found a string/data instead.", underlyingError: nil))
コード
swift
1do{ 2 let json = try JSONSerialization.jsonObject(with: data!,options: []) 3 print(json) 4}catch{ 5 print("error:\(error)") 6}
json
1{"data":{"task":[{"id":"4","task":"\u5b85\u914d\u30dc\u30c3\u30af\u30b9\u306e\u78ba\u8a8d","category":"\u5bb6\u4e8b"},{"id":"6","task":"\u30b8\u30e3\u30ac\u30a4\u30e2","category":"\u8cb7\u3044\u7269"},{"id":"7","task":"\u30d7\u30ed\u30b0\u30e9\u30df\u30f3\u30b0\u3092\u3059\u308b","category":"\u52c9\u5f37"},{"id":"8","task":"\u30d7\u30ed\u30b0\u30e9\u30df\u30f3\u30b0\u3092\u3059\u308b","category":"\u52c9\u5f37"},{"id":"9","task":"\u304a\u98a8\u5442\u306e\u6383\u9664","category":"\u5bb6\u4e8b"}]}}
swift
1//用意した構造体 2struct result: Codable{ 3 let data: Data? 4 struct Data: Codable{ 5 let task: [Task]? 6 struct Task: Codable{ 7 let id: Int? 8 let task: String? 9 let categry: String? 10 } 11 } 12}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。