teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

サンプルコードを追加

2021/12/06 11:45

投稿

退会済みユーザー
answer CHANGED
@@ -10,4 +10,64 @@
10
10
  HTTPステータスコードも確認した方が良いと思いました。
11
11
  その前に、対象のURLをブラウザなどからアクセスしてデータを確認した方が良いと思いました。
12
12
 
13
- それから、`struct`の部分は可読性が悪いですので、入れ子にせずにフラットにした方が良いと思いました。
13
+ それから、`struct`の部分は可読性が悪いですので、入れ子にせずにフラットにした方が良いと思いました。
14
+
15
+
16
+ ---
17
+
18
+ 追記です。
19
+
20
+ 私の手元ではアプリIDを発行していないからか、ブラウザーから次のURLにアクセスするとエラーのJSONが返ってきます。
21
+
22
+ ```
23
+ https://app.rakuten.co.jp/services/api/IchibaItem/Search/20170706?format=json&keyword=楽天&genreId=555086&applicationId=22b18d36ec9a7962a03724e281adb5d1
24
+ ```
25
+
26
+ ```json
27
+ {"error_description":"specify valid applicationId","error":"wrong_parameter"}
28
+ ```
29
+
30
+
31
+ APIテストフォームからテストするとサンプルのJSONが表示できるようです。
32
+
33
+ 楽天ウェブサービス(RAKUTEN WEBSERVICE) : APIテストフォーム
34
+ https://webservice.rakuten.co.jp/explorer/api/IchibaItem/Search/
35
+
36
+ ```
37
+ https://app.rakuten.co.jp/services/api/IchibaItem/Search/20170706?format=json&keyword=%E6%A5%BD%E5%A4%A9&genreId=555086&applicationId=67d6ed870f57df66c1d78f321dffa542
38
+ ```
39
+
40
+ ```json
41
+ {
42
+ "GenreInformation": [],
43
+ "Items": [
44
+ {
45
+ "Item": {
46
+ "affiliateRate": 15,
47
+ ```
48
+
49
+
50
+ サンプルのJSONをもとにまずはJSONDecoderを実装するところから始めてみてはいかがでしょうか。
51
+
52
+ https://developer.apple.com/documentation/foundation/jsondecoder
53
+
54
+ ```swift
55
+ struct GroceryProduct: Codable {
56
+ var name: String
57
+ var points: Int
58
+ var description: String?
59
+ }
60
+
61
+ let json = """
62
+ {
63
+ "name": "Durian",
64
+ "points": 600,
65
+ "description": "A fruit with a distinctive scent."
66
+ }
67
+ """.data(using: .utf8)!
68
+
69
+ let decoder = JSONDecoder()
70
+ let product = try decoder.decode(GroceryProduct.self, from: json)
71
+
72
+ print(product.name) // Prints "Durian"
73
+ ```