一个最易用的Dart JSON响应包装库!
1. 关于
JsonResponse是一个开源的Dart库。
使用JsonResponse,您可以轻松安全地处理您应用程序中的JSON响应。
该库的创建目标是使JSON响应在Dart语言中更易于使用、更直观、更安全。例如,作为与Web API通信过程的结果,JSON从http包返回,并且当JSON被设置为Response时,您以前编写过以下过程,对吗?
final json = jsonDecode(response.body);
final something = json['key'] ?? '';
有了JsonResponse,上述实现不再必要!
1.1. 简介
1.1.1. 安装库
使用 Dart
dart pub add json_response
使用 Flutter
flutter pub add json_response
1.1.2. 导入它
import 'package:json_response/json_response.dart';
1.1.3. 使用JsonResponse
import 'dart:typed_data';
import 'package:json_response/json_response.dart';
void main() {
// It provides constructors to get JSON from JSON string, JSON map, and JSON bytes.
final jsonFromString = JsonResponse.fromString(value: '{"test": "something"}');
final jsonFromMap = JsonResponse.fromMap(value: {'test': 'something'});
final jsonFromBytes = JsonResponse.fromBytes(
value: Uint8List.fromList('{"test": "something"}'.codeUnits));
// You can use handful methods in the same interface once instance is created.
print(jsonFromString.getString(key: 'test'));
print(jsonFromMap.getString(key: 'test'));
print(jsonFromBytes.getString(key: 'test'));
final testJson = JsonResponse.fromMap(
value: {
'testValueList': ['value1', 'value2'],
'testJsonString': '{"key1": "value2"}',
'testJsonList': [
{
'key1': 'value1',
'key2': 'value2',
}
],
'testRecursiveJsonList': [
[
{
'key1': 'value1',
'key2': 'value2',
}
],
{
'key3': 'value3',
'key4': 'value4',
}
]
},
);
if (testJson.isEmpty) {
// Do something when json is empty.
return;
}
// It provides features to safely get values from JSON.
print(testJson.getStringValues(key: 'testValueList'));
// You can easily get a JSON object or JSON list associated with a key.
// If the JSON object associated with the key is a string,
// it will be automatically detected and parsed into a JSON object.
print(testJson.getJson(key: 'testJsonString'));
print(testJson.getJsonList(key: 'testJsonList'));
// If your JSON list is nested, that's okay!
// All JSON expressions associated with a key will be returned as JSON objects.
print(testJson.getJsonList(key: 'testRecursiveJsonList'));
}
1.2. 许可证
Copyright (c) 2021, Kato Shinya. All rights reserved.
Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
1.3. 更多信息
JsonResponse由Kato Shinya设计和实现。