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?
In order to check the validity of a string whether it is a JSON string or not, We’re using the JSON.parse () method with few variations. This method parses a JSON string, constructs the JavaScript value or object specified by the string.
JSON Decode Online is easy to use tool to decode JSON data, view JSON data in hierarchy and show as json_decode php. Copy, Paste, and Decode. What can you do with json_decode? It helps to decode your JSON data. It also works as to view JSON in hierarchy form. This tool allows loading the JSON URL. Use your JSON REST URL to decode.
When working with raw JSON values in Java, sometimes there is a need to check whether it is valid or not. There are several libraries that can help us with this: Gson, JSON API, and Jackson. Each tool has its own advantages and limitations.
That Number is implicitly converted to String within the JSON.parse function, but that does not change the fact that 1234 is not JSON.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With