Question

I need to generate JSON of the POST data and get an exception.

This is the dictionary with a "records" key, that contains an array of NSManagedObjects.

It seems it is throwing an exception when parsing it into json.

NSData *postData = [NSJSONSerialization dataWithJSONObject:[super requestData] options:0 error:&error];

enter image description here

It fails with the following exception. Any idea why this is happening?

'NSInvalidArgumentException', reason: 'Invalid type in JSON write (FTRecord)'
*** First throw call stack:
(
    0   CoreFoundation                      0x01aae5e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x018318b6 objc_exception_throw + 44
    2   CoreFoundation                      0x01aae3bb +[NSException raise:format:] + 139
    3   Foundation                          0x015760f0 _writeJSONValue + 771
    4   Foundation                          0x0157a470 ___writeJSONArray_block_invoke + 129
    5   CoreFoundation                      0x01b2b05d __53-[__NSArrayI enumerateObjectsWithOptions:usingBlock:]_block_invoke + 61
    6   CoreFoundation                      0x01b2af92 -[__NSArrayI enumerateObjectsWithOptions:usingBlock:] + 258
    7   CoreFoundation                      0x01aa80a5 -[NSArray enumerateObjectsUsingBlock:] + 53
    8   Foundation                          0x0157a381 _writeJSONArray + 275

FTRecord:

@interface FTRecord : NSManagedObject

@property (nonatomic) BOOL isRealEntry;
@property (nonatomic) NSTimeInterval timestamp;
@property (nonatomic, retain) NSString * notes;
@property (nonatomic) double orderingValue;
@property (nonatomic) int16_t rating;
@property (nonatomic) NSTimeInterval recordDate;

@end
Was it helpful?

Solution

From the docs, NSManagedObject doesn't meet NSJSONSerialization's criteria for valid objects:

An object that may be converted to JSON must have the following properties:

The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull. All dictionary keys are instances of NSString. Numbers are not NaN or infinity.

You can test this by calling isValidJSONObject:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top