【问题标题】:ObjectMapper how can I map value In a nested EntityObjectMapper 如何在嵌套实体中映射值
【发布时间】:2018-04-27 10:55:28
【问题描述】:

在这种情况下使用ObjectMapper

[{
"port": "1",
"b": [{
     "c": [{"address": 1}]
     }]
}, {
"port": "2",
"b": [{
     "c": [{"address": 2}]
     }]
}]

这里 C 是具有行地址和端口的实体。现在使用 ObjectMapper 如何设置端口实体 C 的值。

我已经编写了这段代码的嵌套部分

class a: NSManagedObject, Mappable {
 @NSManaged var port: NSNumber?
 @NSManaged var b: NSSet?
 private var barr: [b]?
 required public init?(map: Map) {
   let ctx = DbHelper .getContext()
   let entity = NSEntityDescription.entity(forEntityName: "a", in: ctx)
   super.init(entity: entity!, insertInto: ctx)
   mapping(map: map)
}

public func mapping(map: Map) {
  port <- map["port"]
  barr <- map["b"]
  if barr != nil
  {
      b = NSSet(array: barr!)
      barr = nil
  }
 }
}

类似地为“B”和“C”实体创建和映射

现在在“C”,我需要实体“a”的“端口”值。

【问题讨论】:

  • 到目前为止你累了什么?
  • @AhmadF 编辑了问题,添加了我目前实施的内容。

标签: swift core-data objectmapper


【解决方案1】:

第一件事是您的 json 无效。你忘记了" 后端口:"port: "2",

解决办法

模型结构:

class Port : Mappable {
 var port:String?
 var b: [C]?

 required init?(map: Map) {

 }

 func mapping(map: Map) {
    port <- map["port"]
    b <- map["b"]
 }
}

class C : Mappable {
 var c:[Address]?

 required init?(map: Map) {

 }

 func mapping(map: Map) {
    c <- map["c"]
 }
}

class Address : Mappable {
 var address:Int?

 required init?(map: Map) {

 }

 func mapping(map: Map) {
    address <- map["address"]
 }
}

这样称呼它:

if let json = "yourJson" {
                if let res:[Port] = Mapper<Port>().mapArray(JSONArray: json as! [[String : Any]]) {
                    //your port objects
                }
            }

注意:我做了一个强制施法。你不应该。 Objectmapper 需要[[String : Any]] 格式的json

我建议使用 Alamofire 来处理请求。

与 Alamofire 一起使用:

    let url = "https://api.myjson.com/bins/iw6vj" //your json
    Alamofire.request(url).responseJSON { (data) in
        if let json = data.result.value {
            if let res:[Port] = Mapper<Port>().mapArray(JSONArray: json as! [[String : Any]]) {
                //your port objects
            }
        }
    }

如果您处于项目的开始阶段,您应该使用 Codabale https://developer.apple.com/documentation/swift/codable。网上有很多教程。搜索 Alamofire+Codable 可以很轻松的处理请求+解析。

提示:您的命名非常混乱。看看这篇文章https://medium.com/coding-skills/clean-code-101-meaningful-names-and-functions-bf450456d90c这对模型结构也有帮助。

【讨论】:

  • 感谢您的回答,但我想知道如何通过在 C 类中创建对象端口来将端口的值从类端口存储到 C 类。
  • 你能帮我看看如何在核心数据中使用可编码和存储自定义对象吗?
  • 不,我不能。当您遇到特定问题时,我可以帮助您。核心数据的教程很多:medium.com/@kf99916/…google 初击。搜索core data codable swift
  • 我发现我正在谷歌上检查可编码的 coredata,但对于这个特定问题,我将如何通过在 C 类中创建对象端口来将端口的值从类端口存储到 C 类。
猜你喜欢
  • 2018-04-29
  • 1970-01-01
  • 2019-08-03
  • 2023-01-05
  • 2017-09-11
  • 2022-08-13
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多