Thursday, April 30, 2026
HomeiOS Developmentios - Convert to codable object?

ios – Convert to codable object?

[ad_1]

I am attempting to transform [Hit] (a library class) to [Person] object. However no thought how to do this. Can somebody assist me?

Here is Hit class.

public struct Hit<T: Codable> {

  public let objectID: ObjectID
  public let object: T


  public let snippetResult: TreeModel<SnippetResult>?
  public let highlightResult: TreeModel<HighlightResult>?
  public let rankingInfo: RankingInfo?
  public let geolocation: SingleOrList<Level>?

  public let reply: Reply?

}

extension Hit: Equatable the place T: Equatable {}

extension Hit: Codable {

  enum CodingKeys: String, CodingKey {
    case objectID
    case snippetResult = "_snippetResult"
    case highlightResult = "_highlightResult"
    case rankingInfo = "_rankingInfo"
    case geolocation = "_geoloc"
    case reply = "_answer"
  }

  public init(from decoder: Decoder) throws {
    self.object = strive T(from: decoder)
    let container = strive decoder.container(keyedBy: CodingKeys.self)
    self.objectID = strive container.decode(ObjectID.self, forKey: .objectID)
    self.snippetResult = strive container.decodeIfPresent(TreeModel<SnippetResult>.self, forKey: .snippetResult)
    self.highlightResult = strive container.decodeIfPresent(TreeModel<HighlightResult>.self, forKey: .highlightResult)
    self.rankingInfo = strive container.decodeIfPresent(RankingInfo.self, forKey: .rankingInfo)
    self.geolocation = strive? container.decodeIfPresent(SingleOrList<Level>.self, forKey: .geolocation)
    self.reply = strive container.decodeIfPresent(forKey: .reply)
  }

  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    strive container.encodeIfPresent(objectID, forKey: .objectID)
    strive container.encodeIfPresent(objectID, forKey: .objectID)
    strive container.encodeIfPresent(snippetResult, forKey: .snippetResult)
    strive container.encodeIfPresent(highlightResult, forKey: .highlightResult)
    strive container.encodeIfPresent(rankingInfo, forKey: .rankingInfo)
    strive container.encodeIfPresent(geolocation, forKey: .geolocation)
    strive container.encodeIfPresent(reply, forKey: .reply)
    strive object.encode(to: encoder)
  }

}

JSON class

public enum JSON: Equatable {
  case string(String)
  case quantity(Double)
  case dictionary([String: JSON])
  case array([JSON])
  case bool(Bool)
  case null
}


public extension JSON {

  init<T: JSONRepresentable>(_ jsonRepresentable: T) {
    self = jsonRepresentable.json
  }

  init<T: RawRepresentable>(_ rawJsonRepresentable: T) the place T.RawValue: JSONRepresentable {
    self = rawJsonRepresentable.rawValue.json
  }

  init<S: Sequence>(jsonSequence: S) the place S.Aspect: JSONRepresentable {
    self = .array(jsonSequence.map(.json))
  }

  init(_ intValue: Int) {
    self = .quantity(Double(intValue))
  }

  init(_ floatValue: Float) {
    self = .quantity(Double(floatValue))
  }

  init(_ doubleValue: Double) {
    self = .quantity(doubleValue)
  }

  init(_ stringValue: String) {
    self = .string(stringValue)
  }

  init(_ boolValue: Bool) {
    self = .bool(boolValue)
  }

}

extension JSON: ExpressibleByStringInterpolation {

  public init(stringLiteral worth: String) {
    self = .string(worth)
  }

}

extension JSON: ExpressibleByFloatLiteral {

  public init(floatLiteral worth: Double) {
    self = .quantity(worth)
  }

}

extension JSON: ExpressibleByIntegerLiteral {

  public init(integerLiteral worth: Int) {
    self = .quantity(Double(worth))
  }

}

extension JSON: ExpressibleByBooleanLiteral {

  public init(booleanLiteral worth: Bool) {
    self = .bool(worth)
  }

}

extension JSON: ExpressibleByDictionaryLiteral {

  public init(dictionaryLiteral parts: (String, JSON)...) {
    self = .dictionary(.init(uniqueKeysWithValues: parts))
  }

}

extension JSON: ExpressibleByArrayLiteral {

  public init(arrayLiteral parts: JSON...) {
    self = .array(parts)
  }

}

extension JSON: ExpressibleByNilLiteral {

  public init(nilLiteral: ()) {
    self = .null
  }

}

extension JSON {

  public subscript(_ key: String) -> JSON? {
    guard case .dictionary(let dictionary) = self else { return nil }
    return dictionary[key]
  }

  public subscript(_ index: Int) -> JSON? {
    guard case .array(let array) = self else { return nil }
    return array[index]
  }

}

extension JSON: Codable {

  public func encode(to encoder: Encoder) throws {
    swap self {
    case let .array(array):
      strive array.encode(to: encoder)
    case let .dictionary(dictionary):
      strive dictionary.encode(to: encoder)
    case let .string(string):
      strive string.encode(to: encoder)
    case let .quantity(quantity):
      strive quantity.encode(to: encoder)
    case let .bool(bool):
      strive bool.encode(to: encoder)
    case .null:
      var container = encoder.singleValueContainer()
      strive container.encodeNil()
    }
  }

  public init(from decoder: Decoder) throws {

    let container = strive decoder.singleValueContainer()

    if let object = strive? container.decode([String: JSON].self) {
      self = .dictionary(object)
    } else if let array = strive? container.decode([JSON].self) {
      self = .array(array)
    } else if let string = strive? container.decode(String.self) {
      self = .string(string)
    } else if let bool = strive? container.decode(Bool.self) {
      self = .bool(bool)
    } else if let quantity = strive? container.decode(Double.self) {
      self = .quantity(quantity)
    } else if container.decodeNil() {
      self = .null
    } else {
      throw DecodingError.dataCorrupted(
        .init(codingPath: decoder.codingPath, debugDescription: "Invalid JSON worth.")
      )
    }
  }
}

extension JSON: CustomDebugStringConvertible {

  public var debugDescription: String {
    swap self {
    case .string(let str):
      return str.debugDescription
    case .quantity(let num):
      return num.debugDescription
    case .bool(let bool):
      return bool.description
    case .null:
      return "null"
    default:
      let encoder = JSONEncoder()
      encoder.outputFormatting = [.prettyPrinted]
      return (strive? encoder.encode(self)).flatMap { String(information: $0, encoding: .utf8) } ?? ""
    }
  }
}

extension JSON {

  public init(jsonObject: Any) throws {
    let information = strive JSONSerialization.information(withJSONObject: jsonObject, choices: [])
    let decoder = JSONDecoder()
    self = strive decoder.decode(JSON.self, from: information)
  }

  public func object() -> Any? {
    swap self {
    case .null:
      return nil
    case .string(let string):
      return string
    case .quantity(let quantity):
      return quantity
    case .bool(let bool):
      return bool
    case .array(let array):
      return array.map { $0.object() }
    case .dictionary(let dictionary):

      var resultDictionary = [String: Any]()
      for (key, worth) in dictionary {
        resultDictionary[key] = worth.object()
      }
      return resultDictionary
    }
  }

}

extension JSON {

  public init<E: Encodable>(_ encodable: E) throws {
    let information = strive JSONEncoder().encode(encodable)
    let jsonDecoder = JSONDecoder()
    self = strive jsonDecoder.decode(JSON.self, from: information)
  }

}

extension Dictionary the place Key == String, Worth == Any {

  public init?(_ json: JSON) {
    guard case let .dictionary(dict) = json else {
      return nil
    }
    var resultDictionary = [String: Any]()
    for (key, worth) in dict {
      resultDictionary[key] = worth.object()
    }
    self = resultDictionary
  }

}

extension Array the place Aspect == Any {

  public init?(_ json: JSON) {
    guard case let .array(array) = json else {
      return nil
    }
    self = array.compactMap { $0.object() }
  }

}

public protocol JSONRepresentable {

  var json: JSON { get }

}

extension String: JSONRepresentable {

  public var json: JSON { .string(self) }

}

extension Int: JSONRepresentable {}
extension Int8: JSONRepresentable {}
extension Int16: JSONRepresentable {}
extension Int32: JSONRepresentable {}
extension Int64: JSONRepresentable {}
extension UInt: JSONRepresentable {}
extension Double: JSONRepresentable {}
extension Float: JSONRepresentable {}

public extension Numeric the place Self: JSONRepresentable, Self: BinaryInteger {

  var json: JSON { .quantity(Double(self)) }

}

public extension FloatingPoint the place Self: JSONRepresentable, Self: BinaryFloatingPoint {

  var json: JSON { .quantity(Double(self)) }

}

extension Bool: JSONRepresentable {

  public var json: JSON { .bool(self) }

}

extension Sequence the place Aspect: JSONRepresentable {

  public var json: JSON { .init(jsonSequence: self) }

}

extension RawRepresentable the place RawValue: JSONRepresentable {

  public var json: JSON { .init(self) }

}

Individual class

class Individual: Codable {
    var title : String?
    var age : String?
    
    
    required init?(map: Map){}
    init() {}
    
    func mapping(map: Map) {
        title <- map[“Name”]
        age <- map[“AGE”]
    }

}

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments