我想反序列化一組 JSON 物件。我按照Flutter 檔案中的本教程進行操作。問題是,這個陣列嵌套在另一個物件中,看起來像這樣:
{
"result":
{
"array":
[
{
"id": 0,
"name": "here goes the string"
},
{
"id": 1,
"name": "another one here"
} ...
我一直在關注這個官方教程,但我遇到了一個錯誤:
I/flutter (28639): AsyncSnapshot<List>(ConnectionState.done, null, Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' 沒有具有匹配引數的實體方法 'cast'。
I/flutter (28639):接收者:_LinkedHashMap len:2
I/flutter (28639):嘗試呼叫:cast<Map<String, dynamic>>()
I/flutter (28639): 發現: cast<Y0, Y1>() => Map<Y0, Y1>, #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:68:5)
我希望我對.result.array[]反序列化 JSONMap<String, dynamic>的參考很差,盡管錯誤在前面出現了一行,我完全不知道是什么原因造成的。這個例外的原因可能是什么,我是否以一種好的方式參考陣列?
我的應用程式基本上看起來像這樣(我已經標記了箭頭(→)引發例外的行:
/* [...] */
Future<List<Models.Degree>> fetchDegrees(http.Client client) async
{
final response = await client
.get(Uri.parse("api uri here"));
// Using the compute function to run in a separate isolate.
return compute(parseDegrees, response.body);
}
List<Models.Degree> parseDegrees(String responseBody)
{
→ final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed['result']['array'].map<Models.Degree>((json) => Models.Degree.fromJson(json)).toList();
}
/* [...] */
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Models.Degree>>(
future: fetchDegrees(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) {
print(snapshot.toString());
return const Center(
child: Text('An error has occurred!'),
);
} else if (snapshot.hasData) {
return DegreesList(degrees: snapshot.data!);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
class DegreesList extends StatelessWidget {
const DegreesList({Key? key, required this.degrees}) : super(key: key);
final List<Models.Degree> degrees;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: degrees.length,
itemBuilder: (context, index) {
return Text(degrees[index].name);
},
);
}
}
uj5u.com熱心網友回復:
在該教程中,回應正文是:
[
{
"albumId": 100,
"id": 4999,
"title": "in voluptate sit officia non nesciunt quis",
"url": "https://via.placeholder.com/600/1b9d08",
"thumbnailUrl": "https://via.placeholder.com/150/1b9d08"
},
{
"albumId": 100,
"id": 5000,
"title": "error quasi sunt cupiditate voluptate ea odit beatae",
"url": "https://via.placeholder.com/600/6dd9cb",
"thumbnailUrl": "https://via.placeholder.com/150/6dd9cb"
}
]
該jsonDecode方法回傳dynamic。
在這種情況下,型別是List<dynamic>。List 有一個方法cast https://api.dart.dev/stable/2.14.4/dart-core/List/cast.html。所以它作業正常。
但是在您的情況下:
{
"result": {
"array": [
{
"id": 0,
"name": "here goes the string"
},
{
"id": 1,
"name": "another one here"
}
]
}
}
jsonDecode 回傳 _InternalLinkedHashMap 并且它沒有cast方法,因此它會引發例外。
你有很多選擇,只是提一下:
只需洗掉它.cast<Map<String, dynamic>>(),它就可以正常作業。
您不必強制轉換responseBody即可使用它,因為“array”json 鍵的型別List<dynamic>在末尾,因此您可以map毫無問題地使用該方法。
但是,如果你想投那個,你可以使用
final parsed = Map<String, dynamic>.from(jsonDecode(responseBody));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/408828.html
標籤:
