wvteijlingen / Spine

A Swift library for working with JSON:API APIs. It supports mapping to custom model classes, fetching, advanced querying, linking and persisting.
MIT License
266 stars 109 forks source link

Complex attributes with subobject #64

Closed alak closed 8 years ago

alak commented 8 years ago

Hey,

I'm wondering if there is a way to parse subobject in attributes like :

{
    "data": {
        "type": "posts",
        "id": "671",
        "attributes": {
            "id": 671,
            "title": "funy place",
            "location": {
                "name": "La Sorbonne, Paris",
                "short_name": "La Sorbonne",
                "latitude": 52.377965,
                "longitude": 4.912809,
                "distance_from_me": 9125000
            }
        }
    }
}

Thanks

wvteijlingen commented 8 years ago

This should be possible using a custom attribute type and matching formatter. It depends on how you want to represent the nested data in your client. It should be something like this:

class LocationAttribute: Attribute {}

struct  LocationValueFormatter: ValueFormatter {
    func unformat(value: AnyObject, attribute: LocationAttribute) ->  AnyObject {
        // Convert from serialised form to deserialised form
    }

    func format(value: AnyObject, attribute: LocationAttribute) -> AnyObject {
        // Convert from deserialised form to serialised form
    }
}

spine.registerValueFormatter(LocationValueFormatter())
alak commented 8 years ago

Thanks, perfect

wvteijlingen commented 8 years ago

Cool, let me know if there's any trouble :).

gbejarano01 commented 8 years ago

@wvteijlingen I'm trying something like this but it's not working.

Let's say in this case I'm creating a custom Object "Location" with all the properties from location node in the json.

Then when I declare the type of location it's "Location" so when you define unformat it's returning an object "Location" and when defining format the parameter is type "Location" and returns String.

I'm getting a message:

this class is not key value coding-compliant for the key location

gbejarano01 commented 8 years ago

@Alak Did this work for you?

gbejarano01 commented 8 years ago

I think I fixed it, by declaring the property as AnyObject, the problem is when you want to use the property you have to unwrap it as the type you need.

wvteijlingen commented 8 years ago

What kind of type is Location?

gbejarano01 commented 8 years ago

Location should be a custom Class called Location that contains all the properties of the location node in the Json file.

I could fix this, the only issue is that is not letting me declare that as a Location property in my Resource Object, I need to declare it as AnyObject, otherwise I get:

this class is not key value coding-compliant for the key location