Start a new topic

Relational Data - Invalid type in JSON write (KCSKinveyRef)

I am new to Kinvey but I am experiencing difficulties using Relational Data

- I am using KinveyKit-1.40.4

- I am following the steps outlined in

- I am using KCSLinkedAppdataStore

- I have confirmed that both entities are configured correctly and save individually but when I attempt to update them with a relationship (single or multiple) I get an exception.

'NSInvalidArgumentException', reason: 'Invalid type in JSON write (KCSKinveyRef)'

Can anyone suggest a possible solution? I am missing an important step?

2 people have this question

Hi there Richard, 

There was a bug in version 1.40.4 of our iOS library which is updated in the most recent update.   Can you please give that a shot and try it out?


I have update to 1.40.5 and I am able to add singular entity relationships e.g. event.invitee = firstInvitation however when I attempt to map to an NSMutableSet of multiple entities e.g. event.invitees = [firstInvitation] I receive the error

'Invalid type in JSON write (KCSKinveyRef)'

Do I need to change to configuration of kinveyPropertyToCollectionMapping,  kinveyObjectBuilderOptions or referenceKinveyPropertiesOfObjectsToSave to solve this issue?


P.S. Do anyone have a generic sample projects that demonstrates how to setup this up?

1 person likes this

I am still getting the exact same error when trying to create related objects and save. I am using 1.40.5 as well.

 This is my code snippet: KCSQuickle has an array to KCSQuickleItems -- both are collections in by Data Store.

class KCSQuickle: NSObject {
    static let collectionName = "Quickles"
    static let titleField = "title"
    static let itemsField = "items"
    var entityId: String?               // Kinvey entity _id
    var title: String                   // Title of the quickle
    var contributors: [KCSUser]?        // Array of contributors who liked
    var likes: [KCSUser]?               // Array of users who liked
    var metadata: KCSMetadata?          // Create, Updated and Creator
    var items: [KCSQuickleItem]      // Referenced of type KCSQuickleItem

    private override init() {
        title = ""
        items = [KCSQuickleItem]()
    convenience init(titleString: String) {
        title = titleString
    override func hostToKinveyPropertyMapping() -> [NSObject : AnyObject]! {
        return [
            "entityId" : KCSEntityKeyId,
            "title" : KCSQuickle.titleField,
            "items" : KCSQuickle.itemsField,
            "metadata" : KCSEntityKeyMetadata,
    static override func kinveyPropertyToCollectionMapping() -> [NSObject : AnyObject]! {
        return [
            // backend to collection name
            KCSQuickle.itemsField : KCSQuickleItem.collectionName
    static override func kinveyObjectBuilderOptions() -> [NSObject : AnyObject]! {
        return [
            KCS_REFERENCE_MAP_KEY : [
                // property name to object
                "items" : KCSQuickleItem.self
    override func referenceKinveyPropertiesOfObjectsToSave() -> [AnyObject]! {
        // array of backend property names to save
        return [ KCSQuickle.itemsField ]

class KCSQuickleItem: NSObject {
    static let collectionName = "QuickleItem"
    static let itemDescriptionField = "item_description"
    var entityId: String?           // Kinvey entity _id
    var itemDescription: String?

    override func hostToKinveyPropertyMapping() -> [NSObject : AnyObject]! {
        return [
            "entityId" : KCSEntityKeyId,
            "itemDescription" : KCSQuickleItem.itemDescriptionField

 I try to save it as:


let store = KCSQuickle.getLinkedStore()
                        store.saveObject(self.quickle, withCompletionBlock: { (saveResults, saveError) -> Void in
if (saveError == nil) {
// do stuff
}, withProgressBlock: nil)


1.40.5 seems to have fixed relational data for 1-to-1 relationships e.g. user: KCSUser = KCSUser.activeUser() the problem occurs when attempting to store multiple references in an array e.g. users: [KCSUser] = [KCSUser.activeUser()

static override func kinveyPropertyToCollectionMapping() -> [NSObject : AnyObject]! {

 return ["user" : KCSUserCollectionName, "users" : KCSUserCollectionName]


1 person likes this

Even 1-to-1 relational data has issues. Attempting to load an entity with saved relational data using the loadObjectWithID method causes a crash 

reason: 'Invalid type in JSON write (EventPlanner.DressCode)

However fetching the same entity using an exact match query works fine

Richard:  We really discourage against heavy leveraging of relational data and strongly encourage the use of Flat architectures that encourage normalizing your objects rather than using relational querying.  Since the schema can change at any time by modifying your queries having multiple tables and foreign key constraints becomes really unnecessary, and thus relational data being saved into a single object rather than across multiple tables becomes both sensible and easier than trying to use KinveyReferences. 

That said, there are hard limits on how many KinveyRef's can be resolved in a single query (I think it's 99), are you sure that you're not going above that?


1 person likes this

Can anyone confirm if one-to-many relational data are working correctly with the iOS SDK or if this is a bug with the current version (1.40.5)?

I have been through the data store tutorial several times and I am able store an Event with a UCSUser however when I attempt to store multiples it fails.

I have attached my sample code, the code below works

var invitations: KCSUser?

event.invitations = KCSUser.activeUser()

but fails when changed to...

var invitations: [KCSUser]?

event.invitations = [KCSUser.activeUser()]

Is there an additional step I am missing?


KCSUser.activeUser() can be nil, so you need to check for that first.  It should be something more along the lines of:

if let user = KCSUser.activeUser() { event.invitations = [user] }

Does this make sense?




Makes sense, I can confirm I am verifying an activeUser exists in the controller class before calling the save.

And what is the exact error that you're getting and what is the calling context of it?

I have attached a file containing the view controller, Event and Invitation classes.

didTapSaveUser works (sets a single KCSUser)

didTapSaveUsers does not work (sets KCSUser array)

They use the same saveEvent helper method, am I missing something in the Event class to support saving an array?

I've also been having trouble getting "to-many" relationships to work in my Swift project. In order to get to the bottom of the situation, I created a project with KinveyKit 1.40.5, using the Events and Invitations example from the Data Store guide.

I created exact copies of the Event and Invitation code from the example, except for the use of "private" in the override methods, which is no longer used in Swift (you'd use "internal" for subclass-only access).

I discovered there is at least one bug in KinveyKit: The mapping system doesn't pick up properties defined as `NSInteger?` (the Invitation.status property, for example). When you try to save, you get the error: "Entity does not have property 'status' as specified in hostToKinveyPropertyMapping", which is especially annoying when you're looking right at it in your hostToKinveyPropertyMapping. My current workaround is to change the property to a `String?`.

Once I did that, I was able to save entities with a to-one relationship. For example, if I instantiate an event, and an invitation, and I set `invitation.event = event`, I am able to save succesfully, and both the event and invitation are persisted in my Kinvey db.

However, if I try setting the to-many property of the event, it fails, e.g. `event.invitations = NSMutableSet(array: [invitationA, invitationB]`.

Like Richard, I get: "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (KCSKinveyRef)'... libc++abi.dylib: terminating with uncaught exception of type NSException"

Here are links to my code. As I said, it's mostly copied directly from the tutorial. Can anyone see a problem with the way I'm instantiating and saving the entities?

Event class:

Invitation class:

Saving from VC:

I've continued researching the situation, and I've learned a few things.

First, my comment about a bug in KinveyKit's mapping was wrong. KinveyKit's mapping is just fine, when you are using the allowed data types, as specified here: The Invitation example just has a mistake: the "status" property should be a NSNumber rather than an NSInteger.

Second, I've discovered two specific situations where saving objects with relationships fails with 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (KCSKinveyRef).

One: All "to-many" relationships specified by setting a property as an NSMutableDictionary.

Two: "To-one" relationships where the referenced entity itself has references to other entities. (Lets call them ReferencedEntity and SubReferencedEntities)

I read through the section of the guide about Recursive Relationships, and since I'm not using those, I wouldn't expect the SubReferencedEntities to be saved, but I was under the impression that the ReferencedEntity should be saved with the KinveyRef. At I don't think it should cause a fatal error.

I also tried removing any autosaving references (by removing them from from the ReferencedEntity's referenceKinveyPropertiesOfObjectsToSave), and that had no effect.

I uploaded my simple project to GitHub. Would anyone mind taking a look to see if I'm missing something? If not, could someone explain exactly what's causing the error?

Here's the GiHub repo:

Login or Signup to post a comment