23

My cache class

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

In the get method ,I want to see if value can be json.decode what should I do?

sunmoon
  • 355
  • 1
  • 4
  • 8

2 Answers2

50

Just try to decode it and catch FormatException to know when it failed:

void main() {
  var jsonString = '{"abc';
  var decodeSucceeded = false;
  try {
    var decodedJSON = 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');
}
valerybodak
  • 4,195
  • 2
  • 42
  • 53
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
3

I like something that looks like int.tryParse(data). So I using this.

import 'dart:convert';

class Json {
  static String? tryEncode(data) {
    try {
      return jsonEncode(data);
    } catch (e) {
      return null;
    }
  }

  static dynamic tryDecode(data) {
    try {
      return jsonDecode(data);
    } catch (e) {
      return null;
    }
  }
}

Using like this.

void main() {
  String? jsonEncode = Json.tryEncode(dataEncoded);
  if (jsonEncode == null) {
    print("jsonEncode is null");
  } else {
    print("jsonEncode is not null");
  }

  dynamic jsonDecode = Json.tryDecode(dataDecoded);
  if (jsonDecode == null) {
    print("jsonDecode is null");
  } else {
    print("jsonDecode is not null");
  }
}

Caution: When you use Json.tryDecode( jsonEncode(null) ) that function can't tell you if this can convert to JSON or not because the result always is null. But I don't worry about this.