前几天在IOS开发时发现一个JSON解析奇葩问题

iOS 码拜 8年前 (2016-03-21) 901次浏览
前几天在IOS开发时发现一个JSON解析奇葩问题,会出现一定概率的错误,如下:

//出现BUG的条件必须是两位数,且带两位小数,类型还必须是float
    //两位数:十位必须是7、8、9;个位数随意
    //两位小数:个位数随意;十位数必须是0
    NSString *jsonStr = @"{"71.40":71.40, "97.40":97.40, "80.40":80.40, "188.40":188.40}";
    NSLog(@"json:%@", jsonStr);
    NSData *jsonData_ = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *jsonParsingError_ = nil;
    NSDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:jsonData_ options:0 error:&jsonParsingError_]];
    NSLog(@"dic:%@", dic);
    /*结果:dic:{
     "188.40" = "188.4";
     "71.40" = "71.40000000000001";
     "80.40" = "80.40000000000001";
     "97.30" = "97.3";
     }*/

各位高手可是试试,初步怀疑是系统API内部处理问题。

解决方案

5

数据格式错误吧

10

晕死,看一下API吧,是你参数传递错误额
/* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil.
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
*/
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
说的很明白的阿,当参数不是一个数组,或字典的时候,opt才会传0阿。

5

//解析json数据,使用系统方法 JSONObjectWithData:  options: error:
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明前几天在IOS开发时发现一个JSON解析奇葩问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)