如何判断字符串是否可以是json.decode

时间:2018-11-02 04:17:01

标签: dart flutter

我的缓存类

import 'dart:async';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class CacheUtil{
  static set(String key, value) async{
    if(value is Map || value is List){
      value = json.encode(value);
    }
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString(key, json.encode(value));
  }
  static get(String key) async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    String data = preferences.getString(key);
    return data;
  }
}

在get方法中,我想看看value是否可以是json.decode 我该怎么办?

1 个答案:

答案 0 :(得分:2)

只需尝试对其进行解码并捕获FormatException即可知道它何时失败:

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');
}