質問

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

役に立ちましたか?

解決

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.

他のヒント

-(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;

}

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top