freshOS / Arrow

🏹 Parse JSON with style
MIT License
387 stars 27 forks source link

How do I instantiate a model directly from a string containing json? #40

Closed ntkon closed 6 years ago

ntkon commented 6 years ago

Hi, sorry to ask such a dumb question, but I can't figure out how to do a simple decode from a string containing my json to my model object:

struct doh: Codable {
  var homer = ""
}
extension doh : ArrowParsable {
  public mutating func deserialize(_ json: JSON) {
    homer <-- json["homer"]
  }
}

now to create one:

let myJson = "{ \"homer\": \"simpson\"}"
var aSimpson = doh()
aSimpson.deserialize(JSON(myJson)!)

this doesn't work! How do I create a doh object from the myJson string?

Thanks.

s4cha commented 6 years ago

Hi @ntkon,

You need to go through native JSONSerialization in order for it to work. (Actually this could be a great future improvement to support JSON strings)

Here is the working version:

let myJson = "{ \"homer\": \"simpson\"}"

guard let jsonData = myJson.data(using: .utf8),
    let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers),// as? NSDictionary,
    let json = JSON(jsonObject) else {
    return
}

var aSimpson = doh()
aSimpson.deserialize(json)
print(aSimpson)

Also the aSimpson.deserialize(json) part can be written like:

aSimpson <-- json

Hope this helps :)

ntkon commented 6 years ago

Thanks @s4cha, much appreciated. I'm liking using arrow, ws and stevia - nice tools.

s4cha commented 6 years ago

@ntkon can we close this ?

ntkon commented 6 years ago

Sorry, I forgot to do that. Closed :)