【问题标题】:How to pass JSON response to array with model in swift如何在swift中将JSON响应传递给带有模型的数组
【发布时间】:2021-07-05 06:06:03
【问题描述】:

我的 JSON 响应如下所示:

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

为此我创建了这样的模型:

对于模型中的每个对应值,我将像这样创建:

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 响应.. 但无法添加模型

我收到 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))

请。确实有助于使用模型将 JSON 值添加到数组中......在这种情况下我不能使用可编码的协议

【问题讨论】:

  • 对于那些试图帮助您删除old 问题但几个小时后再次重新发布的人来说,这是非常粗鲁的。
  • 在调用 API 的地方创建一个具有该模型类型的变量并将响应分配给该变量,希望对您有所帮助

标签: arrays json swift model


【解决方案1】:

你可以使用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")
}

控制台输出:

Obj 值:userid:10 requestTitle Title-2 类别 4

Obj 值:userid:10 requestTitle Title-2 类别 4

【讨论】:

  • 这是现有项目..他们已经创建了所有模型..所以我不能使用可编码..请帮助我的代码
  • @iosswift 在你的代码中 for (value) in open { }} 值是一个包含所有 3 个值的字典,所以只需使用下标来访问每个值,然后将其转换为预期的类型,比如 value["title"] as? String 左右,而不是使用接收到的值创建你的ServicesModel
  • 我应该在模型中的哪个变量中添加value["title"] as? String,这件事我做不到
  • 你有ServicesModel init,它接受 3 个值,所以创建局部变量(初始化所需的一切),然后将它们传递给 ServicesModel 的构造函数,如 let title = value["title"] as? String 和其他值然后ServicesModel(header: title,...)
  • 是的,我可以使用局部变量..但我需要使用模型..我需要向模型添加 JSON 响应..并在每个地方调用它们(比如打开..我有close 和 all ) 选项,所以我也需要显示它的值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 2021-02-22
  • 2018-12-08
  • 2013-04-29
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多