“Unexpected Character” on Decoding JSON

前端 未结 4 1522
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 04:21

The following is the code:

    static TodoState fromJson(json) {
          JsonCodec codec = new JsonCodec();
            List data = codec.decod         


        
4条回答
  •  旧巷少年郎
    2021-01-03 04:59

    There's a problem with your code as well as the string you're trying to parse. I'd try to figure out where that string is being generated, or if you're doing it yourself post that code as well.

    Valid Json uses "" around names, and "" around strings. Your string uses nothing around names and '' around strings.

    If you paste this into DartPad, the first will error out while the second will succeed:

    import 'dart:convert';
    
    void main() {
      JsonCodec codec = new JsonCodec();
      try{
        var decoded = codec.decode("[{id:1, text:'fdsf', completed: false},{id:2, text:'qwer', completed: true}]");
        print("Decoded 1: $decoded");
      } catch(e) {
        print("Error: $e");
      }
    
      try{
        var decoded = codec.decode("""[{"id":1, "text":"fdsf", "completed": false},{"id":2, "text":"qwer", "completed": true}]""");
        print("Decoded 2: $decoded");
      } catch(e) {
        print("Error: $e");
      }
    }
    

    The issue with your code is that you expect the decoder to decode directly to a List. It will not do this; it will decode to a dynamic which happens to be a List whose items happen to be Map.

    See flutter's Json documentation for information on how to handle json in Dart.

提交回复
热议问题