iosobjective-cnsjsonserializationnsvalue

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteValue)


This is my dictionary:

 { @"RoutePolyline":<__NSArrayM 0x283983750>(<c59272f7 39263940      55a4c2d8 42f65240>),
    @"RideID":6565
};

I am sending this dictionary as an argument in my API call.

and my app crashes at this line of code:

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

This is the error it throws:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteValue)'

I know the RoutePolyline parameter is holding a NSValue (it is supposed to be an array of coordinates) and not any object type, but I have tried converting alot, but nothing have worked so far. For example

[NSValue valueWithMKCoordinate:*routeCoordinates]

Solution

  • Loop through your NSValue array and extract CLLocationCoordinate2D's value.

    for (NSValue *value in coordinates) {
        CLLocationCoordinate2D coordinate;
        [value getValue:&coordinate];
        NSDictionary *coDic = @{@"latitude" : [NSNumber numberWithDouble: coordinate.latitude],
                                @"longitude": [NSNumber numberWithDouble: coordinate.longitude]};
        [array addObject:coDic];
    }
    

    Also Check if dictionary is valid JSON before serialize

    if ([NSJSONSerialization isValidJSONObject:dic]) {
        NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    }