簡體   English   中英

如何在 swift 中使用 model 將 JSON 響應傳遞給數組

[英]How to pass JSON response to array with model in swift

我的 JSON 響應如下所示:

"result": {
    "data": {
        "open": [
            {
                "user_id": "10",
                "request_title": "Title-2",
                "category": "4"
            }
            {
                "user_id": "10",
                "request_title": "Title-2",
                "category": "4"
            }.....
            ]

為此,我創建了這樣的 MODEL:

對於 model 中的每個對應值,我將創建如下:

public class Result {
public var status : Status?
public var data : PostedData?

public class func modelsFromDictionaryArray(array:NSArray) -> [Result]
{
    var models:[Result] = []
    for item in array
    {
        models.append(Result(dictionary: item as! NSDictionary)!)
    }
    return models
}


required public init?(dictionary: NSDictionary) {

    if (dictionary["status"] != nil) { status = Status(dictionary: dictionary["status"] as! NSDictionary) }
    if (dictionary["data"] != nil) { data = PostedData(dictionary: dictionary["data"] as! NSDictionary) }
}


public func dictionaryRepresentation() -> NSDictionary {

    let dictionary = NSMutableDictionary()

    dictionary.setValue(self.status?.dictionaryRepresentation(), forKey: "status")
    dictionary.setValue(self.data?.dictionaryRepresentation(), forKey: "data")

    return dictionary
}

}

這是 PostedData:

public class PostedData {
public var open : [Open]?
public var all : [All]?

required public init?(dictionary: NSDictionary) {

    if (dictionary["open"] != nil) { open = Open.modelsFromDictionaryArray(array: dictionary["open"] as! NSArray) }

    if (dictionary["all"] != nil) { all = All.modelsFromDictionaryArray(array: dictionary["all"] as! NSArray) }
}
}


public class Open {
public var user_id : String?
public var request_title : String?
}

我能夠得到 JSON 響應.. 但無法添加 MOdel

在這里我得到 JSON 響應:

          var postModel: PostedServiceBase?

     if let code = ((resp.dict?["result"] as? [String : Any])){
     // here i am trying to add JSON resp to model
     self?.postModel = PostedServiceBase(dictionary: resp.responseDict as? NSDictionary ?? NSDictionary())                    
     let totalData = code["data"] as? [String : Any]
      if let open = totalData?["open"] as? [[String : Any]]{
      for (value) in open {
                    
            }
        }
      

在這里我需要將open數組值添加到servicesArray .. 但是我怎么做不到

  self?.servicesArray.append(ServicesModel(header: self?.allValues?.request_title, title: self?.allValues?.request_title, userId: self?.allValues?.userid))

請。 幫助使用 model 將 JSON 值添加到數組中......在這種情況下我不能使用可編碼協議

U 可以使用JSONDecoder將 json 轉換為對象:

import Foundation

let json = """
    {
    "result": {
      "data": {
        "open": [
          {
            "user_id": "10",
            "request_title": "Title-2",
            "category": "4"
          },
          {
            "user_id": "10",
            "request_title": "Title-2",
            "category": "4"
          }
        ]
       }
      }
    }
"""

print(json)

struct TestJSON: Codable {
  var result: Result
}

struct Result: Codable {
  var data: DataClass
}

struct DataClass: Codable {
  var dataOpen: [Open]

  enum CodingKeys: String, CodingKey {
    case dataOpen = "open"
  }
}

struct Open: Codable {
  var userid: String
  var requestTitle: String
  var category: String

  enum CodingKeys: String, CodingKey {
    case userid = "user_id"
    case requestTitle = "request_title"
    case category
  }
}

extension Open: CustomDebugStringConvertible {
  var debugDescription: String {
    "userid: " + userid + " " +
      "requestTitle " + requestTitle + " " +
        "category " + category
  }
}

extension DataClass: CustomDebugStringConvertible {
  var debugDescription: String {
    dataOpen
      .map{ "Obj value: " + $0.debugDescription }
      .joined(separator: "\n")
  }
}

extension Result: CustomDebugStringConvertible {
  var debugDescription: String {
    data.debugDescription
  }
}

extension TestJSON: CustomDebugStringConvertible {
  var debugDescription: String {
    result.debugDescription
  }
}

let jsonData = json.data(using: .utf8)
if let jsonData = jsonData {
  let jsonDecoder = JSONDecoder()
  do {
    let testJSON = try jsonDecoder.decode(TestJSON.self, from: jsonData)
    print(testJSON)
  } catch {
    print(error)
  }
} else {
  print("can't convert json string into data")
}

控制台中的 Output:

Obj 值:用戶 ID:10 requestTitle Title-2 類別 4

Obj 值:用戶 ID:10 requestTitle Title-2 類別 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM