I want to pass a nested json object from JavaScript context to a Capacitor plugin. No nested objects are working. When nested, I'm struggling with the JSValue that I cannot cast into a dictionary.
@objc(MyPlugin)
public class MyPlugin: CAPPlugin {
@objc func start(_ call: CAPPluginCall) {
let fooCAP: JSObject = call.getObject("foo")!
let foo: Foo = // ?
}
}
public struct Foo: Decodable {
let bar: Bar
}
public struct Bar: Decodable {
let color: String
}
I can get the bar value with fooCAP["bar"]
, but I can't get the color value with fooCAP["bar"]["color"]
because fooCAP["bar"]
is of type JSValue.
The documentation says, I should use .toDictionary()
, but this function doesn't exist.
How can I convert the JSObject into my struct?
CodePudding user response:
Example:
if let bar = fooCAP["bar"] as? JSObject {
if let color = bar["color"] as? String {
// Do something
}
}
Here you can find another example on GitHub.