Tusshu
Tusshu

Reputation: 1734

json.Decode error: FormatException: Unexpected character (at character 3)

I want to get list of companies from Mongo db and use it in Flutter application.

Dart server has following code to fetch data from mongo and send it to client:

var list = await db.collection('employers').find().toList();
... convert Object id to id string...
return Response.ok(list.toString(),
    headers: {'Content-Type': 'application/json', ...corsHeaders});

The following data is received at the client:

[{name: IBM, id: 60bea5624986930dec6f8c7a}, {name: HP, id: 60bea5754986930dec6f8c7b}]

I need to create Dart list of companies from the above data. Tried the following code:

var list = json.decode(data).cast<List<Map<String, dynamic>>>();

But is generates the following error:

FormatException (FormatException: Unexpected character (at character 3)
error pointer is at [{n

Help please!

Upvotes: 0

Views: 887

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17133

[{name: IBM, id: 60bea5624986930dec6f8c7a}, {name: HP, id: 60bea5754986930dec6f8c7b}]

This is not a valid JSON. This is expected as you never actually encoded a JSON. You just do list.toString() for some reason.

Encode your JSON on your server:

return Response.ok(jsonEncode(list),
    headers: {'Content-Type': 'application/json', ...corsHeaders});

Upvotes: 4

Related Questions