How to convert a Dictionary to a JsonElement or something an any JsonElementable ?
mackoj opened this issue Β· comments
Hi @KittyMac,
Thank you for providing this excellent library. I like it so much that I praised it on the Swift forum π https://forums.swift.org/t/wouldnt-jsonpatch-jsonpointer-be-better-in-foundation/67109/5
I seem to be having trouble creating a JsonElement
from a [String: String]
or any Dictionary
type. Perhaps I'm missing something. Could you please help me figure out how to do it?
When performing this operation: JsonElement(unknown: elementable)
where elementable
is either a [String: String]
or a [String: AnyHashable]
.
I'm encountering this issue:
error: expression failed to parse:
Spanker.Dictionary<String, Optional<JsonElementable>>:4294967293:11: note: requirement from conditional conformance of '[String : String]' to 'JsonElementable'
extension Dictionary : Spanker.JsonElementable where Key == String, Value == Spanker.JsonElementable? {
^
error: <EXPR>:8:29: error: class 'JsonElement' requires the types 'String' and '(any JsonElementable)?' be equivalent
JsonElement(unknown: config.value)
^
Spanker.Dictionary<String, Optional<JsonElementable>>:1:11: note: requirement from conditional conformance of '[String : String]' to 'JsonElementable'
extension Dictionary : Spanker.JsonElementable where Key == String, Value == Spanker.JsonElementable? {
Thank you,
-- Jeff
Thanks, should be fixed now (v0.4.22).
The main issue is in Spanker I avoid the use of as? in almost all instances, which means our protocol conformance needs to be known/inferable at compile time. String is not the same as JsonElementable? (note the optional), but even if I temporarily remove the optional the error will be String is not the same as "any JsonElementable". Note that this all worked if pass directly into the function JsonElement(unknown: ["a":"b"]), where the compiler can infer the correct types.
Since the creation of JsonElements by unknown is outside of the "fast path" (ie parsing JsonElements from Data or String), I have relaxed the as? rule for this case. Array and Dictionary will be loaded in dynamically now, and any values which cannot as? to a JsonElementable will be set to null in the resultant object. It is advisable that if you are loading large amount of data this was it is going to be faster if you load directly from the source Data/String json.
Thanks π