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

前端 未结 8 2162
南旧
南旧 2021-02-04 01:05

I\'m getting this exception when I try to JSON encode NSDate object.I believe NSDate is not compatible for JSON encoding. but I must encode the date.Any solutions?



        
相关标签:
8条回答
  • 2021-02-04 01:29

    For our case, we are using Mantle to convert an object to JSON and one of our objects with property NSDate is missing its JSONTransformer

    @property (nonatomic) NSDate *expiryDate;
    

    where:

    + (NSValueTransformer *)expiryDateJSONTransformer {
         return [MTLValueTransformer transformerUsingForwardBlock:^id(NSString *dateString, BOOL *success, NSError *__autoreleasing *error) {
            return [self.dateFormatter dateFromString:dateString];
        } reverseBlock:^id(NSDate *date, BOOL *success, NSError *__autoreleasing *error) {
            return [self.dateFormatter stringFromDate:date];
        }];
    }
    
    + (NSDateFormatter *)dateFormatter {
        NSDateFormatter *df = [NSDateFormatter new];
        df.dateFormat = @"yyyy-MM-dd";
        return df;
    }
    
    0 讨论(0)
  • 2021-02-04 01:30

    I am doing something like this in my body params encoder

    // handle dates
                  var _params = [String: Any]()
                  params.forEach { (key, value) in
                    if let date = value as? Date {
                        _params[key] = DateFormatter.iso8601Full.string(from: date)
                    } else {
                        _params[key] = value
                    }
                  }
    
                  return try? JSONSerialization.data(withJSONObject: _params)
    
    0 讨论(0)
提交回复
热议问题