thoughtbot/Argo

Parse nested model fails when adding a specific key

dregatos opened this issue · 2 comments

Hi,

I have a nested model with four levels. When I am trying to parse a specific key of the deepest level, named "id", the parser returns nil. When I comment or remove that specific key, everything works fine. I noticed that 3rd and 4th level have a field with the same key, "id"... Any idea about how to get the "id" key-value of the 4th level?

Error Messages

No error message

Sample JSON

{
    "level_two_key": {
        "a_key": <value>,
        ...
        "level_three_key": [
            {
                "id": 4050,
                ...
                "level_four_key": [
                    {
                        "id": 20066,
                        "a_key": <value>,
                        ...
                    }
                ]
            }
        ]
    },
    "another_level_two_key": <value>
}

Models

struct LevelOneStruct: Argo.Decodable {
	let propertyOne: LevelTwoStruct?
	let propertyTwo: AnotherPropertyStruct?

	init?(propertyOne: LevelTwoStruct?, propertyTwo: AnotherPropertyStruct?) {
		guard propertyOne != nil || propertyTwo != nil else {
			return nil
		}

		self. propertyOne = propertyOne
		self.propertyTwo = propertyTwo
	}

	static func decode(_ json: JSON) -> Decoded<LevelOneStruct> {
		let one: Decoded< LevelTwoStruct > = json <| "level_two_key"
		let two: Decoded< AnotherPropertyStruct > = json <| "another_level_two_key"
		return .fromOptional(self.init(propertyOne: one.value, propertyTwo: two.value))
	}
}

struct LevelTwoStruct: Argo.Decodable {
	<more properties>
	let level_two_property: [LevelThreeStruct]

	static func decode(_ json: JSON) -> Decoded<LevelTwoStruct> {
		return curry(self.init)
			<^> json <| "a_key"
			...
			<*> json <|| "level_three_key"
	}
}

struct LevelThreeStruct: Argo.Decodable {
        let id: Int
	<more properties>
	let property: [LevelFourStruct]

	static func decode(_ json: JSON) -> Decoded<LevelThreeStruct> {
		let new = curry(self.init)
			<^> json <| "id"
			...
		return new
			...
			<*> json <|| "level_four_key"
	}
}

struct LevelFourStruct: Argo.Decodable {
        <more properties>
	let id: Int <– Removing this

	static func decode(_ json: JSON) -> Decoded<LevelFourStruct> {
		return curry(self.init)
			<^> json <| "a_key"
			...
			<*> json <| "id" < – and this, parser works.
	}
}

Argo Version

Argo 3.0.0

Dependency Manager

Carthage

I don't see any obvious answers to this. Have you tried inspecting the result of the decoding to see what the failure was? We include failure information as a part of the Decoded type, so you should be able to get more info there.

I'm going to close the issue because, after modifying the model, I am not able to reproduce the issue anymore 😑 Thank you for your time!