【发布时间】:2019-03-24 00:14:51
【问题描述】:
我正在解码响应正文并收到错误消息:
'List<dynamic>' is not a subtype of type 'List<Example>'
我正在解析 JSON 对象的 JSON 数组,其中一个字段也是对象列表,我怀疑我的问题源于此。我也在使用 json_serializable 库。下面是我的代码,我省略了一些字段并更改了一些变量名,但它代表相同的代码:
import 'package:json_annotation/json_annotation.dart';
part 'example_model.g.dart';
@JsonSerializable()
class Example {
(some fields here)
final List<Random> some_urls;
final List<String> file_urls;
const Example({
(some fields here)
this.some_urls,
this.file_urls,
});
factory Example.fromJson(Map<String, dynamic> json) =>
_$ ExampleFromJson(json);
}
@JsonSerializable()
class Random {
final String field_1;
final int field_2;
final int field_3;
final int field_4;
final bool field_5;
constRandom(
{this.field_1, this.field_2, this.field_3, this.field_4, this.field_5});
factory Random.fromJson(Map<String, dynamic> json) => _$RandomFromJson(json);
}
来自 json_serializable 制作的 .g dart 文件(省略了编码部分):
Example _$ExampleFromJson(Map<String, dynamic> json) {
return Example(
some_urls: (json['some_urls'] as List)
?.map((e) =>
e == null ? null : Random.fromJson(e as Map<String, dynamic>))
?.toList(),
file_urls: (json['file_urls'] as List)?.map((e) => e as String)?.toList(),
}
Random _$RandomFromJson(Map<String, dynamic> json) {
return Random(
field_1: json['field_1'] as String,
field_2: json['field_2'] as int,
field_3: json['field_3'] as int,
field_4: json['field_4'] as int,
field_5: json['field_5'] as bool);
}
这是我未来的功能:
Future<List<Example>> getData(int ID, String session) {
String userID = ID.toString();
var url = BASE_URL + ":8080/example?userid=${userID}";
return http.get(url, headers: {
"Cookie": "characters=${session}"
}).then((http.Response response) {
if (response.statusCode == 200) {
var parsed = json.decode(response.body);
List<Example> list = parsed.map((i) => Example.fromJson(i)).toList();
return list;
}
}).catchError((e)=>print(e));
}
【问题讨论】: