本文介绍了无法将JSON解析中的NSNumber桥接到Float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出现此错误:

这是原始消息,它是浮点数而不是字符串.

This is the original message, it is float and not string.

{\"name\":\"Tomas\",\"gender\":\"male\",\"probability\":0.99,\"count\":594}

推荐答案

在Swift/Foundation中,您有许多不同类型的数字.您的NSKeyValueCoding已设置为NSNumber的实例(请参见下面的JSON序列化文档摘录),因此您需要按原样阅读,然后根据需要要求将此NSNumber转换为Float:

You have many different types of numbers in Swift/Foundation. Your NSKeyValueCoding has been set as instance of NSNumber (see excerpt of JSON serialization documentation below) so you need to read as is, and then ask to convert this NSNumber as Float if needed:

if let n = d.value(forKey: "probability") as? NSNumber {
    let f = n.floatValue
}

JSONSerialization文档说:

  • 顶级对象是NSArray或 NSDictionary.
  • 所有对象都是NSString, NSNumber , NSArray,NSDictionary或NSNull.
  • 所有字典键都是NSString的实例.
  • 数字不是NaN或无穷大.
  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.

这篇关于无法将JSON解析中的NSNumber桥接到Float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 08:51