2017-12-29 23 views
1

서버에서 JSON을 파싱하는 데 도움이 필요합니다. 여기에 JSON입니다 : "텍스트", "의견", "재 게시", "첨부 파일", "좋아"Codable을 사용하여 Swift 4에서 복잡한 JSON을 구문 분석하는 방법

{ 
"response": { 
    "items": [ 
     { 
      "type": "post", 
      "source_id": -17507435, 
      "date": 1514538602, 
      "post_id": 4105, 
      "post_type": "post", 
      "text": "Some text here", 
      "marked_as_ads": 0, 
      "attachments": [ 
       { 
        "type": "photo", 
        "photo": { 
         "id": 456239655, 
         "album_id": -7, 
         "owner_id": -17507435, 
         "user_id": 100, 
         "photo_75": "https://sun1-3.userapi.com/c840632/v840632924/3b7e7/4YUS7DlaLK8.jpg", 
         "photo_130": "https://sun1-3.userapi.com/c840632/v840632924/3b7e8/Ffpb4ZUlulI.jpg", 
         "photo_604": "https://sun1-3.userapi.com/c840632/v840632924/3b7e9/-pkl6Qdb9hk.jpg", 
         "width": 439, 
         "height": 312, 
         "text": "", 
         "date": 1514538602, 
         "post_id": 4105, 
         "access_key": "6a61a49570efd9c39c" 
        } 
       } 
      ], 
      "post_source": { 
       "type": "api" 
      }, 
      "comments": { 
       "count": 0, 
       "groups_can_post": true, 
       "can_post": 1 
      }, 
      "likes": { 
       "count": 0, 
       "user_likes": 0, 
       "can_like": 1, 
       "can_publish": 1 
      }, 
      "reposts": { 
       "count": 0, 
       "user_reposted": 0 
      }, 
      "views": { 
       "count": 2 
      } 
     } 
    ], 
    "profiles": [], 
    "groups": [ 
     { 
      "id": 17507435, 
      "name": "Literature Museum", 
      "screen_name": "samlitmus", 
      "is_closed": 0, 
      "type": "group", 
      "is_admin": 0, 
      "is_member": 1, 
      "photo_50": "https://pp.userapi.com/c615722/v615722068/e58c/d5Y8E_5689s.jpg", 
      "photo_100": "https://pp.userapi.com/c615722/v615722068/e58b/Hm05ga3x2J8.jpg", 
      "photo_200": "https://pp.userapi.com/c615722/v615722068/e589/yoG_DDalFII.jpg" 
     }, 
     { 
      "id": 27711883, 
      "name": "E:\\music\\melodic hardcore", 
      "screen_name": "e_melodic_hc", 
      "is_closed": 0, 
      "type": "page", 
      "is_admin": 0, 
      "is_member": 1, 
      "photo_50": "https://pp.userapi.com/c628220/v628220426/47092/xepNnC7pSBw.jpg", 
      "photo_100": "https://pp.userapi.com/c628220/v628220426/47091/uAokr-c3NQ8.jpg", 
      "photo_200": "https://pp.userapi.com/c628220/v628220426/4708f/eNY4vzooz4E.jpg" 
     }, 
     { 
      "id": 81574241, 
      "name": "DOS4GW.EXE", 
      "screen_name": "dos4gw", 
      "is_closed": 0, 
      "type": "page", 
      "is_admin": 0, 
      "is_member": 1, 
      "photo_50": "https://pp.userapi.com/c622118/v622118651/e045/vlhV6QxtoLI.jpg", 
      "photo_100": "https://pp.userapi.com/c622118/v622118651/e044/P9mVUhXBV58.jpg", 
      "photo_200": "https://pp.userapi.com/c622118/v622118651/e043/Soq8oxCMB0I.jpg" 
     }, 
     { 
      "id": 76709587, 
      "name": "Prosvet", 
      "screen_name": "prosvet_pub", 
      "is_closed": 0, 
      "type": "page", 
      "is_admin": 0, 
      "is_member": 0, 
      "photo_50": "https://pp.userapi.com/c630431/v630431500/b24a/GHox8AmDTXU.jpg", 
      "photo_100": "https://pp.userapi.com/c630431/v630431500/b249/H3mcC-K7htM.jpg", 
      "photo_200": "https://pp.userapi.com/c630431/v630431500/b248/9fyvB8gkcwc.jpg" 
     } 
    ], 
    "next_from": "1/4105_1514494800_5" 
} 

} 나는이 JSON에서 얻을 필요가있는 무엇

라인입니다.

"첨부 파일"입력란에 "photo_604"줄을 가져오고 싶습니다. 여기

내 코드입니다 :

class NewsItems: Decodable { 
    var text: String? 
    var comments: Comments 
    var likes: Likes 
    var reposts: Reposts 
    var attachments: [Attachments] 
} 

class Comments: Decodable { 
    var count: Int? 
} 

class Likes: Decodable { 
    var count: Int? 
} 

class Reposts: Decodable { 
    var count: Int? 
} 

class Attachments: Decodable { 
    var attachments: AttachmentPhoto 
} 

class AttachmentPhoto: Decodable { 
    var photo: WhatIsInsideAttachmentsPhoto 
} 

class WhatIsInsideAttachmentsPhoto: Decodable { 
    var photo: String? 

    enum CodingKeys: String, CodingKey { 
     case photo = "photo_604" 
    } 
} 


class WhatIsIsideResponseNewsFeed: Decodable { 
    var items: [NewsItems] 
} 

public class ResponseNewsFeed: Decodable { 
    var response: WhatIsIsideResponseNewsFeed 
} 

그러나 요청을 한 후 :

Alamofire.request(baseURL+methodName, parameters: parameters).responseData(completionHandler: { response in 
     if let result = response.result.value { 
      let decoder = JSONDecoder() 
      let myResponse = try! decoder.decode(ResponseNewsFeed.self, from: result) 
      completion(myResponse.response.items) 

을 나는 오류 얻을 :

Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(_UL_PetrovLeonid.NewsItems.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).attachments, Swift.DecodingError.Context(codingPath: [_UL_Leonid.ResponseNewsFeed.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).response, _UL_PetrovLeonid.WhatIsIsideResponseNewsFeed.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).items, Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0))], debugDescription: "No value associated with key attachments (\"attachments\").", underlyingError: nil))

이 왜 일어나고 있음을 나는 무엇을해야합니까 그것을 해결합니까? 나는 지금부터 3 개월 밖에 코딩하지 않았으므로 내 문제가 어리 석다면 미리 용서해주십시오.

감사합니다.

답변

0

는 오류 메시지 (... CodingKeys)

... Swift.DecodingError.keyNotFound ... NewsItems.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).attachments ... No value associated with key attachments (\"attachments\").

  • keyNotFound
  • 있는 NewsItem이 누락되어있다. 매우 분명하다NewsItems의 주요 attachments에 대한 개체입니다 .attachments하는 입니다. Attachments
  • 키 첨부와 관련된 값이 없습니다 (\ "a ttachments \ ")은 무엇을 말합니다.

간략한 설명 : attachmentsAttachments의 키가 없습니다. 당신의 JSON에서

봐는

 "attachments": [ 
      { 
       "type": "photo", 
       "photo": { 

클래스에 해당 사실 class ES를 사용할 필요에 없다

class AttachmentPhoto: Decodable { 

    private enum CodingKeys : String, CodingKey { 
     case photo604 = "photo_604" 
     case id 
    } 

    let id : Int 
    let photo604 : String // or even URL 
    // etc. 
} 

있어야하는데

class Attachments: Decodable { 
    let type : String 
    let photo : AttachmentPhoto 
} 

그리고 AttachmentPhoto입니다 대부분의 경우 struct이면 충분합니다.

+0

감사합니다, vadian, 대답은 오류를 해결했습니다! 나 같은 신입 사원에게는 그런 것을 간과하기 쉽습니다. –