Error with NSJSONSerialization - Invalid type in JSON write (Menu)

后端 未结 4 1196
南方客
南方客 2020-12-03 00:22

I have an App using core data with 3 entities with very similar attributes. The relationship is such as:

Branch ->> Menu ->> Category ->> FoodItem

Each ent

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 00:58

    There is a class method isValidJSONObject on NSJSONSerialization that tells you if a object can be serialised. As Julien pointed out you probably have to convert your object to a NSDictionary. NSManagedModel provides some handy methods to get all your attributes for your entity. So you could create a category for NSManagedObject that has a method to convert it over to a NSDictionary. This way you don't have to write a toDictionary method for each entity you want to convert to a dictionary.

    @implementation NSManagedObject (JSON)
    
    - (NSDictionary *)toDictionary
    {
        NSArray *attributes = [[self.entity attributesByName] allKeys];
        NSDictionary *dict = [self dictionaryWithValuesForKeys:attributes];
        return dict;
    }
    

提交回复
热议问题