安全轻松地从 Map/JSON 中检索值,并提供有用且人性化的错误消息。只需稍加努力,您就可以解析并保证值的类型。

特点

Retriever 在解析 Map 中的值时主要有 2 个功能

1. 自动错误处理

  // This method will throw an error if the value is invalid
  Retriever.getString('key', map);

  // This method will return null if the value is invalid
  Retriever.getMaybeString('key', map);

2. 真正有用的错误

  RetrieverFormatError: Found invalid format when parsing key.
       Key: "name"
       Expected: "Integer"
       Found: "String", value: "myExampleName".
       Object: "{
                --> name: myExampleName
                    ^^^^
                    age: 40
                }"

使用 retriever,您可以安全地解析

  • 字符串
  • 整数
  • Double(双精度浮点数)
  • 日期
  • 地图

入门

Retriever 除了 Dart 本身之外没有其他依赖项,并且所有方法都是静态的。这使得它易于使用且性能良好。

用法

给定以下 Map。

  final map = {
    'name': 'myExampleName',
    'age': 40,
  };

您可以通过这种方式从 Map 中检索字符串。

  final string = Retriever.getString('name', map);
  print(string); // 'myExampleName'

如果键不存在或值无效,将抛出错误。这些错误非常有用且易于人类阅读,准确地显示了正在发生的事情。

  // Using getString on a "int" value will throw the following error
  Retriever.getString('age', map); // 'age' is a int. error will be thrown

  //  RetrieverFormatError: Found invalid format when parsing key.
  //       Key: "name"
  //       Expected: "Integer"
  //       Found: "String", value: "myExampleName".
  //       Object: "{
  //                --> name: myExampleName
  //                    ^^^^
  //                    age: 40
  //                }"

附加信息

如果您发现问题,请随时提交 issue进行 pull request

All contributions are welcome ?

GitHub

查看 Github