在Flutter中,无论我尝试解码哪个json文件,我都得到相同的标题错误。 最初,我认为这与我的项目有关,但是在启动新的模板Flutter项目后,我仍然收到相同的错误。我的根文件夹中有json文件,并将它们添加到pubspec.yaml文件中:
assets:
- Sample-JSON-data.json
- Sample-employee-JSON-data.json
当前的Main.dart代码:
var jsonString = 'Sample-JSON-data.json';
var response = jsonDecode(jsonString);
print(response);
我已经在多个测试站点上验证了我的json数据,并在Flutter Documentation中尝试了各种方法。杰森数据:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
151.0763783444317,
-33.98045132346684
]
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
151.07774912725728,
-33.97470462237792
]
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
151.07774912725728,
-33.97470462237792
]
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
151.07774912725728,
-33.97470462237792
]
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
151.0763783444317,
-33.98045132346684
]
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
151.07774912725728,
-33.97470462237792
]
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
151.07774912725728,
-33.97470462237792
]
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
151.07774912725728,
-33.97470462237792
]
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
151.0763783444317,
-33.98045132346684
]
}
}
]
}
答案 0 :(得分:2)
jsonDecode
期望输入是有效的JSON,序列化为String fe。
{ "message": "Hello World!" }
。这样就可以了:jsonDecode('{"message": "Hello World!"}')
。
您要传递给它的是文件名,它不会自动为您读取文件。您可以在此处检查操作方法:
答案 1 :(得分:1)
实际上,您不是从json文件中加载数据。
尝试:
var jsonString = await rootBundle.loadString('Sample-JSON-data.json')