Reputation: 3255
I'm using the JSON framework in Obj-C (iOS) to parse responses from a RESTful webservice (C#/.NET).
The framework is fine when it comes to arrays or objects, but one of the service calls is returning a string:
Raw value (in memory on the server):
41SIdX1GRoyw1174duOrewErZpn/WatH
JSON value in the http response once encoded by WCF:
"41SIdX1GRoyw1174duOrewErZpn\/WatH"
This is processed OK by counterpart JSON frameworks on Android, Windows Phone 7 and, of course, jQuery. The server also sometimes returns a .NET WebFaultException, which would automatically serialize an error message as "Error message here"
.
The JSON Framework comes back with an error: Token 'string' not expected before outer-most array or object
Anyone know how can I decode a javascript string in Objective C?
thanks Kris
Upvotes: 0
Views: 1977
Reputation: 3255
-(NSString*)handleResponseAsString:(NSString*)data{
if(data==nil || [data length] == 0) return nil;
NSString* retVal = nil;
SBJsonParser* parser = [[SBJsonParser alloc] init];
NSArray* items = [parser objectWithString:[NSString stringWithFormat:@"[%@]", data]]; // enclose in [] so that the parser thinks it's an array
if([parser error] == nil)
{
if([items count] > 0) retVal = (NSString*) [items objectAtIndex:0];
else NSLog(@"handleResponseAsString parser error: the array had zero elements");
}else{
NSLog(@"handleResponseAsString error: '%@' could not be decoded due to error: %@", data, [parser error]);
}
[parser release];
return retVal;
}
Upvotes: 0
Reputation: 47699
I think you're saying that the JSON framework you're using can't handle a value as the outermost entity in a JSON string -- it expects an object or array. If that's the case, it would be a simple matter to test the first non-whitespace character for either '[' or '{', and, if not one of those, assume it's a value.
Simpler still, you could always enclose the input string in '[' ']' before feeding it to the JSON parser, then "discard" the outer one-element array before observing the data. This lets the JSON parser handle parsing whatever value format is present.
Upvotes: 2