NSObject does not have a member named Key error

夙愿已清 提交于 2019-12-13 07:15:25

问题


I need to construct a JSON object in the format shown below.

{
  "DeviceCredentials": {
    "UniqueId": "sample string 1"
  },
  "Handovers": [
    {
      "Occasions": [
        {
          "Id": 1
        },
        {
          "Id": 1
        }
      ]
    }
  ]
}

There is a issue though with the Occasions array though. The number of Occasion objects vary. Sometimes there can be only one Occasion, sometimes multiple. Since this is dynamic I wrote the below method to create this array.

func getOccasionArray(handover: Handover) -> JSON {
    var occArray = [[String: NSNumber]]()
    for occ in handover.occasions {
        let occasion = occ as Occasion
        var obj = ["Id": occasion.id!]
        occArray.append(obj)
    }
    let json = JSON(occArray)
    return json
}

I use the SwiftyJSON library to convert the created array to JSON. Here's the returned result of json variable looks like for a Handover which has only one Occasion.

[
  {
    "Id" : 243468
  }
]

So far so good. The problem is I'm having trouble plugging this into the bigger JSON response. Simply calling the method like this gives the error 'NSObject' does not have a member named 'Key'.

var parameters = [String: NSObject]()

parameters = [
    "DeviceCredentials": [
        "UniqueId": "1212121212"
    ],
    "Handovers": [
        [
            "Occasions": getOccasionArray(handover)
        ]
    ]
]

I tried converting the returned value to an array getOccasionArray(handover).arrayValue but no change.

Any idea on how to fix this?

Thanks.


回答1:


You don't need SwiftyJSON here then:

Make your 'getOccasionArray' to return a [String: NSObject]

func getOccasionArray(handover: Handover) -> [String: NSObject] {
  var occArray = [[String: NSNumber]]()
  for occ in handover.occasions {
    let occasion = occ as Occasion
    var obj = ["Id": occasion.id!]
    occArray.append(obj)
  }
  return occArray
}

Define parameters as [String: NSObject]:

var parameters = [[String: NSObject]]()

var json: [String: NSObject] = getOccasionArray(handover)        

parameters = [["DeviceCredentials": ["UniqueId": "1212121212"], "Handovers": ["Occasions": json]]]


来源:https://stackoverflow.com/questions/28739509/nsobject-does-not-have-a-member-named-key-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!