Reputation: 31
Hi so I am trying to convert JSON to objects but when I read the file it throws up an exception:
FileSystemException: Cannot open file, path = 'D:/AndroidStudio/my_app/assets/data/questions.json' (OS Error: No such file or directory, errno = 2)
here is the code:
String loadQuestionAsset() {
String jsonString;
new File('D:/AndroidStudio/my_app/assets/data/questions.json').readAsString().then((String contents) {
jsonString = contents;
});
return jsonString;
}
List<Question> parseJsonForQuestion() {
Map decoded = jsonDecode(loadQuestionAsset());
List<Question> questions = new List<Question>();
for (var question in decoded['questions']) {
questions.add(new Question(question['question'], question['bool']));
}
return questions;
}
and the JSON file:
{
"questions": [
{
"question": "Elon Musk is human",
"bool": false
},
{
"question": "Pizza is healthy",
"bool": false
},
{
"question": "Flutter is awesome",
"bool": true
}
]
}
Thanks for help :)
Upvotes: 3
Views: 6408
Reputation: 1
You can do:
String loadQuestionAsset() {
String jsonString;
File('D:/AndroidStudio/my_app/assets/data/questions.json').create().readAsString().then(String contents) {
jsonString = contents;
});
return jsonString;
}
Upvotes: 0
Reputation: 5069
Path you need to provide is: assets/data/questions.json
.
Now, in order to read it, you have to add this also into assets in pubspec.yaml
file.
flutter:
assets:
- data/questions.json
Then, in order to read, you should use rootBundle:
Map map = await rootBundle
.loadStructuredData('assets/data/questions.json', (String s) async {
return json.decode(s);
});
I hope it works :)
Upvotes: 1