Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a string can be json.decode

Tags:

flutter

dart

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?

like image 302
sunmoon Avatar asked Nov 02 '18 04:11

sunmoon


People also ask

How to check if a string is a JSON string?

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.

What can you do with JSON_decode?

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.

How to check if a JSON value is valid in Java?

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.

Why is 1234 not a JSON string?

That Number is implicitly converted to String within the JSON.parse function, but that does not change the fact that 1234 is not JSON.


1 Answers

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');
}
like image 91
Günter Zöchbauer Avatar answered Oct 12 '22 22:10

Günter Zöchbauer