欢迎来到 Parse Data,一个数据解析工具,用于解析JSON中的动态数据,将其转换为预期的类型,以避免向下转型,并在数据解析失败时采取行动。
动机
我曾见过我朋友们的毕业设计项目,他们隐式地向下转型了从JSON接收到的动态数据。
对我来说,这似乎还可以,因为它不像JavaScript那样是动态语言,Dart在类型不匹配时会抛出TypeError。
我唯一担心的是处理不熟悉或不确定的第三方API,因为当开发者不确定数据类型时,可能会出现运行时错误,或者返回的数据可以解析为不同的类型,例如{x: 1}或{x: '1'}。在这种情况下,两者x都可以是整数1,但只需要解析其中一个为int。这不是主要问题,主要问题是当开发者期望整数或数字时,由于数据可能缺失或类型不同,不可避免地会发生运行时异常。
从我所见的来看,隐藏的危险是**向下转型**,无论是隐式的还是显式的。
因此,我们编写了一个工具来检查值的`数据类型`并将其强制转换为预期的类型,否则,可以返回一个备选值,或者抛出一个错误,或者执行一个备选操作。更多信息,请参阅用法。
在这种情况下,隐式向下转型被移除,数据形状也得到了相应的解析。因此,人们可以确信已经进行了适当的验证,并且减少了可能发生的bug。
特点
将动态数据解析为布尔值、字符串、数字、双精度浮点数、整数和特定类型的列表。
请参阅example.dart。
入门
用法
final dynamic json = // some JSON data
// parse
final booleanParser = Parse(json.isHealthy).asBoolean();
// actions
// 1. Return null if it's truly nullable, I won't recommend to use it to represent emptiness
final isHealthy = booleanParser.elseGetNull();
// 2. Return alternative value if it cannot be parsed
final isHealthy = booleanParser.elseGet(false);
// 3. Lazily compute and return alternative value if it's too expenstive to be computed and if value cannot be parsed
final isHealthy = booleanParser.elseLazyGet(() => false);
// 4. Throw error when you are really sure that the field is the type you want and will always be present in JSON
// Again, I would recommend to use it when you wanna throw an exception with custom message
// As Dart will by default throws `TypeError` if data type doesnt match
final isHealthy = booleanParser.elseThrow('damn son');
// 5. Return Wrapper to check if it's parseable, if not, then you handle the alternative action
// The main purpose of this function is to provide developer a more flexible way of handling
// the situation themselves, if it cannot be parsed
// NOTE: If you use this, remember to call `isParseable` first
// Otherwise, you will get an exception, whenever `unwrap` is called and it's not parseable
final booleanWrapper = booleanParser.elseGetWrapper();
if (booleanUnion.isParseable()) {
final isHealthy = booleanWrapper.unwrap()
} else {
// do something else
}
附加信息
您可以在Github上找到我。
您也可以点击这里查看此仓库的源代码。
此外,如果您愿意,也可以贡献,只需:
- 创建并提交到一个新分支。
- 编写测试代码。
- 创建一个Pull Request。
或者
如果您愿意,可以提交issue。