Serialize custom object to JSON which contains NSMutableArray

前端 未结 3 1466
旧巷少年郎
旧巷少年郎 2020-12-22 02:27

I\'m trying to serialize my Cart object which has an NSMutableArray of items in it but getting an:

*** Terminating app due to uncaught exception \

相关标签:
3条回答
  • 2020-12-22 02:40

    NSJSONSerialization only works on arrays (NSArray or NSMutableArray), dictionaries (NSDictionary or NSMutableDictionary, strings (NSString or NSMutableString), and NSNumber.

    The common mechanism is to create a - (NSDictionary *)serialize method on your class that copies all its values into a dictionary to be passed into NSJSONSerialization. Then implement - (id)initFromSerialization:(NSDictionary *)serialization to deserialize the object.

    0 讨论(0)
  • 2020-12-22 02:53

    I know this is kinda late but maybe this class can ease your coding:

    Its a class that transform Custom NSObject to JSON readable object(NSArray or NSDictionary). Have a try and see. It has the capability to skip properties and changed property type from string to NSInteger or Float, it can also changed the final output property name lets say

    CustomObject *X;
        X.property1 = @"Test";
    
    //and the output JSON readable format you want tot change X to Y
    
    //CustomObject converted to readable format
       {Y = @"Test"}
    

    here is the class Disassembler

    0 讨论(0)
  • 2020-12-22 03:01

    This line: [itemsToSerialize addObject:item]; should be [itemsToSerialize addObject:itemDict];. The result is that you're trying to serialize an array of the items themselves, which gives the exception you're seeing.

    0 讨论(0)
提交回复
热议问题