Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)

I find this error to happen to many other users and although trying many of suggested solutions nothing seems to work, so I'm trying to post my specific case.

I'm trying to save an image from iphone application to my postgresql database using django.

my view looks like this:

def objectimages(request, obj_id):
    object = imagesTable.objects.filter(uniqueid=obj_id)
    if request.method == 'POST':
        value = request.POST.get('image')
        f= open('image.txt', 'w+')
        f.write(value)
        f.close()
        object.update(image=value)
        return HttpResponse("Post received")
    elif request.method == 'GET':
        output = serializers.serialize('json',object, fields=('image'),indent=5, use_natural_keys=True)
        return HttpResponse(output, content_type="application/json")
  • the file is just for debug purposes and it seems to write the correct data
  • also tried return HttpResponse({}, content_type="application/json")

in my application the post request is done using AFNetworking like this:

-(void) saveImageToDB
{
    NSString* BaseURLString = POST_IMAGE;

    NSData* data = UIImagePNGRepresentation(self.image);


    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    [manager POST:BaseURLString
       parameters:@{@"image":[data base64EncodedString]}
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSLog(@"image saved successfuly");
         }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error saving image: %@", error)

         }];
}

so I added this line of code

manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

and got this error: Invalid value around character 1

I also try to do:

AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];

[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

manager.requestSerializer = requestSerializer;

which ended up always with The request timed out.

please advice what is wrong with my request

like image 658
Kukula Mula Avatar asked Dec 18 '13 02:12

Kukula Mula


1 Answers

You're returning the string Post received as a response to POST requests. This string is not valid JSON (if you wanted to return just a string in your JSON response, the correct JSON representation would be "Post received", with quotes), and your JSON deserializer seems to complain about exactly that. Try serializing your response in both branches of your logic.

like image 81
lanzz Avatar answered Oct 29 '22 21:10

lanzz