将swifty json数组保存到用户默认值

Dya*_*ana 5 swift alamofire swifty-json

我有一个json data,它提供以下信息:

let data = [
  {
    "QuestionTitle" : "Entomology is the science that studies",
    "Id" : 205,
    "Options" : [
      { "Option" : "Insects", "Id" : 810 },
      { "Option" : "The origin and history of technical and scientific terms", "Id" : 811 },
      { "Option" : "The formation of rocks", "Id" : 812 },
      { "Option" : "Behavior of human beings", "Id" : 809 }
    ]
  },
  {
    "QuestionTitle" : "A train running at the speed of 60 km\/hr crosses a pole in 9 seconds. What is the length of the train?",
    "Id" : 199,
    "Options" : [
      { "Option" : "120 metres", "Id" : 785 },
      { "Option" : "324 metres", "Id" : 787 },
      { "Option" : "180 metres", "Id" : 786 },
      { "Option" : "150 metres", "Id" : 788 }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

我正在使用swiftyjson.我想使用nsuserdefaults保存整个数组.

GlobalVar.defaults.set(json, forKey: "questionArray")
GlobalVar.defaults.synchronize()
Run Code Online (Sandbox Code Playgroud)

但是,我收到一个错误

"[用户默认值]尝试设置非属性列表对象".

请帮助我是新手.我也检查了其他类似的问题,但似乎不起作用.

vad*_*ian 4

您无法保存 SwiftyJSON 的自定义类型JSONUserDefaults但可以保存原始数组,因为反序列化的 JSON 集合类型符合属性列表。

只需调用arrayObjectJSON对象即可:

GlobalVar.defaults.set(json.arrayObject, forKey: "questionArray")
Run Code Online (Sandbox Code Playgroud)