Closed Sina-KH closed 8 years ago
Hi @sina-kh ,
I just tried an example in a test project and I can't unfortunately reproduce the issue :(
According to your example I assume your json looks like so :
{
"customModel": {
"id" : 1234,
"title" : "Great!"
}
}
struct OneModel:ArrowParsable {
var customModel = CustomModel()
init() { }
init(json: JSON) {
customModel <== json["customModel"]
}
}
struct CustomModel:ArrowParsable {
var id = Int()
var title = String()
init() { }
init(json: JSON) {
id <-- json["id"]
title <-- json["title"]
}
}
then I run :
let json:JSON = jsonForName("OneModel")!
let m = OneModel(json: json)
print(m.customModel.id)
print(m.customModel.title)
which prints out :
1234
Great!
Do you have a compiler error? a runtime crash? or something like that ?
Unbelievably It's working now!!! Before this It wasn't parsing! Sorry about that.
But I have another problem bro, How can I parse an array of custom objects with Arrow?
Hey @sina-kh Excuse the late reply. At the moment there is no Arrowish way to easily parse arrays. The way you would do it is the manual way which looks like so :
for a property
var phoneNumbers:[PhoneNumber] = [PhoneNumber]()
and the following JSON
{
"id": 15678,
"created_at": "2013-06-07T16:38:40+02:00",
"name": "Francky",
"stats": {
"numberOfFriends": 163,
"numberOfFans": 10987
},
"phoneNumbers": [{
"label": "house",
"number": "9809876545"
}, {
"label": "cell",
"number": "0908070656"
}, {
"label": "work",
"number": "0916570656"
}]
}
The parsing would be the following :
phoneNumbers = [PhoneNumber]()
if let pns = json["phoneNumbers"] as? [AnyObject] {
for pn in pns {
phoneNumbers.append(PhoneNumber(json: pn))
}
}
of course with the following mapping :
struct PhoneNumber {
var label:String = ""
var number:String = ""
}
extension PhoneNumber:ArrowParsable {
init(json: JSON) {
label <-- json["label"]
number <-- json["number"]
}
}
Hope it helps :)
Actually here is a snippet that would enable parsing arrays with <== syntax :)
public func <== <T:ArrowParsable>(inout left:[T], right: AnyObject?) {
left = [T]()
if let pns = right as? [AnyObject] {
for pn in pns {
left.append(T(json:pn))
}
}
}
Array parsing has been added in the latest version :)
Good to hear that. Finally I can use arrow in my projects easier than ever! Thanks, Good Job!
Hi,
I'm trying to parse my custom models but
<== json["customModel"]
not working for me!Example :
But I can use json.valueForKeyPath without any problems!!!