美文网首页
AFNetworking 怎么解析非 json 的 字符串 返回

AFNetworking 怎么解析非 json 的 字符串 返回

作者: 小专注 | 来源:发表于2018-11-15 16:40 被阅读62次

在其源码里面增加代码,位置为:AFN>Serialization>AFURLResponseSerialization.m 第233行

>这段代码

if(!responseObject) {

responseObject = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];

    }

>这段代码

    if (!responseObject)

    {

        if (error) {

            *error = AFErrorWithUnderlyingError(serializationError, *error);

        }

        return nil;

    }

    if (self.removesKeysWithNullValues) {

        return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);

    }

    return responseObject;

}

下面可以直接替换这个方法体:

#pragma mark - AFURLResponseSerialization

- (id)responseObjectForResponse:(NSURLResponse*)response

                           data:(NSData*)data

                          error:(NSError*__autoreleasing*)error

{

    if(![selfvalidateResponse:(NSHTTPURLResponse*)responsedata:dataerror:error]) {

        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {

            returnnil;

        }

    }

    idresponseObject =nil;

    NSError*serializationError =nil;

    // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.

    // See https://github.com/rails/rails/issues/1742

    BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]];

    if(data.length>0&& !isSpace) {

        responseObject = [NSJSONSerializationJSONObjectWithData:dataoptions:self.readingOptionserror:&serializationError];

    }else{

        returnnil;

    }

    if(!responseObject) {

        responseObject = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    }

    if(!responseObject)

    {    if(error) {

            *error =AFErrorWithUnderlyingError(serializationError, *error);

        }

        return nil;

    }

    if(self.removesKeysWithNullValues&& responseObject) {

        return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);

    }

    returnresponseObject;

}

相关文章

网友评论

      本文标题:AFNetworking 怎么解析非 json 的 字符串 返回

      本文链接:https://www.haomeiwen.com/subject/bswyfqtx.html