Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
ntkon opened this issue Jun 8, 2018 · 4 comments
Closed

Comments

@ntkon
Copy link

ntkon commented Jun 8, 2018

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
Copy link
Member

s4cha commented Jun 12, 2018

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
Copy link
Author

ntkon commented Jun 15, 2018

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

@s4cha
Copy link
Member

s4cha commented Aug 1, 2018

@ntkon can we close this ?

@ntkon
Copy link
Author

ntkon commented Aug 1, 2018

Sorry, I forgot to do that. Closed :)

@ntkon ntkon closed this as completed Aug 1, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants