Dart语言中如何判断一个字符串能否被解析为json
在php中我们可以用如下方法判断一个字符串能不能被解析为json
/**
* 是不是json
* @param $string
* @return bool
*/
function is_json($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
dart中就麻烦了些
import 'dart:convert';
void main() {
var jsonString = '{"abc';
Map<String,dynamic> decodedJSON;
var decodeSucceeded = false;
try {
var x = json.decode(jsonString) as Map<String, dynamic>;
decodeSucceeded = true;
} on FormatException catch (e) {
print('The provided string is not valid JSON');
}
print('Decoding succeeded: $decodeSucceeded');
}