JSONSerialization Invalid type in JSON write (_SwiftValue)

前端 未结 10 958
情书的邮戳
情书的邮戳 2020-12-14 14:14

Why does the following code give me the error:

Invalid type in JSON write (_SwiftValue).

The error is thrown on this line:

10条回答
  •  渐次进展
    2020-12-14 14:32

    You should convert NSObject to NSDictionary at first

    Try this to convert to NSDictionary.

    #import 
    
    //Add this utility method in your class.
    + (NSDictionary *)dictionaryWithPropertiesOfObject:(id)obj {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
        unsigned count;
        objc_property_t *properties = class_copyPropertyList([obj class], &count);
    
        for (int i = 0; i < count; i++) {
            NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
            [dict setObject:[obj valueForKey:key] ? [obj valueForKey:key] : @"" forKey:key];
        }
    
        free(properties);
    
        return [NSDictionary dictionaryWithDictionary:dict];
    }
    

    Then call this:

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&err];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    

提交回复
热议问题