Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Unexpected Character" on Decoding JSON

Tags:

json

flutter

dart

The following is the code:

    static TodoState fromJson(json) {
          JsonCodec codec = new JsonCodec();
            List<Todo> data = codec.decode(json["todos"]);
            VisibilityFilter filter = codec.decode(json['visibilityFilter']);

     return new TodoState(todos: data,
                          visibilityFilter: filter);
  }

Error produced by Android Studio:

[VERBOSE-2:dart_error.cc(16)] Unhandled exception: FormatException: Unexpected character (at character 3)

Any idea how to make it work?

enter image description here

This is the output of the Json as produced by Redux.

like image 407
Mauricio De armas Avatar asked Apr 04 '18 11:04

Mauricio De armas


People also ask

Does JSON parse throw error?

JSON. parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.

What is Jsondecode in flutter?

JsonDecoder class Null safetyThis class parses JSON strings and builds the corresponding objects. A JSON input must be the JSON encoding of a single JSON value, which can be a list or map containing other values. Throws FormatException if the input is not valid JSON text.

What is format exception in flutter?

FormatException class Null safetyException thrown when a string or some other data does not have an expected format and cannot be parsed or processed.


4 Answers

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<dynamic> whose items happen to be Map<String, dynamic>.

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

like image 80
rmtmckenzie Avatar answered Oct 04 '22 02:10

rmtmckenzie


I don't know if that's the case, but I got a similar error when me JSON looks like this

[ { ... }, ]

and not like this

[ { ... } ]

The comma was causing the issue.

like image 28
Adriano Langaro Avatar answered Oct 04 '22 04:10

Adriano Langaro


If Anyone came here and your are using dio package to call http request you need to set responseType to plain

 BaseOptions options = new BaseOptions(
    baseUrl: "<URL>",
    responseType: ResponseType.plain
  );
like image 26
Bawantha Avatar answered Oct 04 '22 03:10

Bawantha


I also have similar type of error, Be make sure that the argument of .decode method shouldn't be empty object.

try {
if(json["todos"].isNotEmpty) {
List<Todo> data = codec.decode(json["todos"]);
}
if(json["todos"].isNotEmpty) {
VisibilityFilter filter = codec.decode(json['visibilityFilter']);
}
}
catch(e) {
print(e);
}

Do try this, hope it will work for you.

like image 36
Parag saini Avatar answered Oct 04 '22 02:10

Parag saini