IOS中 关于JSON解析封装的工具类

声明: 此方法只是简单的利用ios 自带的JSON 工具,对其进行封装。


1. 新建文件 JSONTools.h ,并声明如下文件:

#import

@interfaceJSONTools :NSObject

+ (NSString*)dictToJsonString:(NSDictionary*)dict;

+ (NSDictionary*)parseJsonFromStringOrObject:(NSString*)data;

@end

2.  在 JSONTools.m 文件中的实现如下方法:

#import "JSONTools.h"

@implementation JSONTools

+ (NSString *)dictToJsonString:(NSDictionary *)dict

{

NSString *jsonStr = @"数据异常,无法转成JSON";

BOOL isValidJson =  [NSJSONSerialization isValidJSONObject:dict]; // 校验是否是json

if (isValidJson) {

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];

jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

}

return jsonStr;

}

// 将JSON转成对象

+ (NSDictionary *)parseJsonFromStringOrObject:(NSString *)data

{

NSData *newData = [data dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

NSDictionary  * dict = [NSJSONSerialization JSONObjectWithData:newData options:NSJSONReadingAllowFragments error:nil];

return  dict;

}

@end

3. 测试使用方法:

#import "JSONTools.h"  // 引入文件(第一步)

AFHTTPRequestOperationManager*manager =[AFHTTPRequestOperationManagermanager];// 网络请求代码[manager.securityPolicysetAllowInvalidCertificates:YES];//忽略https证书[manager.securityPolicysetValidatesDomainName:NO];//是否验证域名// manager.requestSerializer = [AFJSONRequestSerializer serializer];//设置请求格式manager.responseSerializer= [AFHTTPResponseSerializerserializer];//设置返回格式manager.responseSerializer.acceptableContentTypes= [manager.responseSerializer.acceptableContentTypessetByAddingObject:@"text/html"];[manager.requestSerializersetValue:[selfgenerateUserAgent]forHTTPHeaderField:@"User-Agent"];

[managerPOST: @"http://www.baidu.com" parameters:nil success:^(AFHTTPRequestOperation*_Nonnulloperation,id_NonnullresponseObject) {

NSString*jsonString = [[NSStringalloc]initWithData:responseObject

encoding:NSUTF8StringEncoding];

NSDictionary*dictJson =[JSONToolsparseJsonFromStringOrObject:jsonString];

NSLog("========dictJson===========",dictJson);

}

failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {

}];







你可能感兴趣的:(IOS中 关于JSON解析封装的工具类)