Swift에서 Json 구문 분석

푸알

Json 파일을 구문 분석하는 데 문제가 있습니다. Json 파일을 구문 분석하십시오.

{
  "id": 1234,
  "lists": {
    "pause": {
      "attached": [
        {
          "from": 1576680044000,
          "to": 1576680055000,
          "length": 11000
        }
      ]
    }
  },
  "time": {
    "start_time": 1576680044000,
    "end_time": 1576680055000
  }
}

여기에 내가 정의한 두 개의 구조체가 있습니다.

구조체 일시 중지 :

public struct Pause: Decodable {

   public let attached: [AttachedModel]

   init(badlAttached: [AttachedModel] = []) {
      self.attached = attached
   }

   private enum CodingKeys: String, CodingKey {
      case attached = "attached"
   }
}

AttachedModel 모델 구조체 :

public struct AttachedModel: Decodable {

   private enum CodingKeys: CodingKey {
      case from, to
   }

   public let range: Range<Int64>

   init(range: Range<Int64>) {
      self.range = range
   }

   public init(from decoder: Decoder) throws {
      do {
         let rootContainer = try decoder.container(keyedBy: CodingKeys.self)
         let from: Int64 = try rootContainer.decode(key: .from)
         let to: Int64 = try rootContainer.decode(key: .to)
         range = from ..< to
      } catch {
         throw JSONDecoder.DecodingError(type: type(of: self), payload: error)
      }
   }
}

그런 다음 키와 함수를 만듭니다.

   enum Key: String {
      case lists
      case pause = "pause"
   }

 func pause() throws -> Pause? {
      let seriesJSON = try lists()
      if let json = seriesJSON[Key.pause.rawValue] as? [String: Any] {
         return try JSONDecoder().decode(Pause.self, from: json) //It's never called
      } else {
         return nil
      }
   }

기능 lists():

func lists() throws -> [String: Any] {
      let json: [String: Any] = try payload.valueForRequiredKey(Key. lists.rawValue)
      return json
   }

다음은 list()

  [1] = {
    key = "pause"
    value = {
      payload_data_0 = 0x0000600001af8a10 {
        ObjectiveC.NSObject = {
          baseNSObject@0 = {
            isa = __NSSingleObjectArrayI
          }
        }
      }
      payload_data_1 = 0x544e786f6a497768
      payload_data_2 = 0x444f3363544e3363
      instance_type = 0x00007fe02f877ed0
    }
  }

문제는 pause데이터 가있는 경우에도이 행은 항상 거짓 if let json = seriesJSON[Key.pause.rawValue] as? [String: Any] {이며 nil여기에 문제가있는 곳을 알려주는 사람이 있습니까?

RA

json에 대한 모델 클래스로 이것을 만듭니다.

import Foundation

class MyItem: Codable {
    let id: Int
    let lists: Lists
    let time: Time
}

class Lists: Codable {
    let pause: Pause
}

class Pause: Codable {
    let attached: [Attached]
}

class Attached: Codable {
    let from, to, length: Int
}

class Time: Codable {
    let start_time, end_time: Int
}

// MARK: - Helper functions for creating encoders and decoders
fileprivate func newJSONDecoder() -> JSONDecoder {
    let decoder = JSONDecoder()
    if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
        decoder.dateDecodingStrategy = .iso8601
    }
    return decoder
}

fileprivate func newJSONEncoder() -> JSONEncoder {
    let encoder = JSONEncoder()
    if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
        encoder.dateEncodingStrategy = .iso8601
    }
    return encoder
}

그런 다음 다음과 같이 구문 분석 할 수 있습니다.

let myItem = try? newJSONDecoder().decode(MyItem.self, from: jsonData)
// Read from (for example)
let from = myItem.lists.pause.attached[0].from

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

AFNetworking에서 JSON 구문 분석-Swift

분류에서Dev

Swift의 OpenWeatherMap에서 JSON 구문 분석

분류에서Dev

Swift로 Json 구문 분석

분류에서Dev

JSON Swift 구문 분석

분류에서Dev

JSON Swift TableView 구문 분석

분류에서Dev

Swift JSON 구문 분석

분류에서Dev

Swift Alamofire JSON 구문 분석

분류에서Dev

PHP에서 JSON 구문 분석 문제

분류에서Dev

powershell에서 json 구문 분석 문제

분류에서Dev

Rails 문제에서 JSON 구문 분석

분류에서Dev

Swift에서 JSON 데이터 (URL에서) 구문 분석

분류에서Dev

Swift 1.2에서 JSON 구문 분석 문제

분류에서Dev

API에서 Swift로 JSON 데이터 구문 분석 문제

분류에서Dev

Json Object Swift 5 내에서 Json 객체 구문 분석

분류에서Dev

Jenkins에서 JSON 개체 구문 분석

분류에서Dev

scala / play에서 "stringified"JSON 구문 분석

분류에서Dev

Microsoft SQL에서 JSON 구문 분석

분류에서Dev

Alamofire에서 responseJSON json 구문 분석

분류에서Dev

SAS에서 JSON 구문 분석

분류에서Dev

jQuery에서 Json 배열 구문 분석

분류에서Dev

Python 및 AngularJS에서 JSON 구문 분석

분류에서Dev

셸에서 JSON 구문 분석

분류에서Dev

jQuery 오류에서 json 구문 분석

분류에서Dev

jQuery에서 JSON 객체 구문 분석

분류에서Dev

Python에서 JSON 구문 분석 오류

분류에서Dev

Android에서 동적 JSON 구문 분석

분류에서Dev

PHP에서 JSON 구문 분석 응답

분류에서Dev

JSON에서 여러 Apis 구문 분석

분류에서Dev

IMDb API에서 JSON 구문 분석