Mingyu Cui
Mingyu Cui

Reputation: 120

Can't use NSJSONSerialization to convert number to JSON value

I need to POST a JSON number value to server, by using AFNetworking, I did it like this :

let url:Int = "my_url_here"
let param = myNumber

let task = self.sessionManager.POST(url, param, success:mySuccessBlock, failure:myFailureBlock)

Got an exception:

'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'

After set a exception breakpoint, code stop at [mutableRequest setHTTPBody...]

#pragma mark - AFURLRequestSerialization
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
                           withParameters:(id)parameters
                                    error:(NSError *__autoreleasing *)error
{
......
**[mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];**
......
}

So [NSJSONSerialization dataWithJSONObject:options:error:] can't be used to convert Int/NSNumber to JSON? What should I do?

Upvotes: 0

Views: 385

Answers (1)

Aaron Brager
Aaron Brager

Reputation: 66302

Minimally valid JSON is {} or []. You need to wrap the number in an object or an array.

Try let param = [myNumber] or let param = ["number" : myNumber], for example.

You can use a tool like JSONLint to validate your JSON.

Upvotes: 2

Related Questions