我将继续我的 Flutter 之旅。我能够在 ListView 中显示一个简单的 json。现在我正在尝试使用带有嵌套对象的 json 但每次运行应用程序时都会出现错误
我正在为 Flutter 官方文档中建议的 json 模型类生成代码。
当我解析用户时,错误似乎发生了。在调试时,我看到 name 和 surname 已成功解析,但是当我跳转到该行的 user.g.dart 中的详细信息对象时:
json['details'] == null
? null
: Details.fromJson(json['details'] as Map<String, dynamic>),
我看到了错误:
type String is not a subtype of type 'Map<String, dynamic>' in type cast
如何解决此错误,以及如何访问所有嵌套对象以显示它们?
这是我必须解析的json。我编辑了它,没有 arename 字段:
数据.json
[
{
"name": "jhon",
"surname": "walker",
"details": "{\"work\":{\"salary\":\"116\",\"company\":\"evolution\"},\"address\":{\"street\":\"grand station\",\"city\":\"salt lake\"}}"
},
{
"name": "peter",
"surname": "parker",
"details": "{\"work\":{\"salary\":\"116\",\"company\":\"evolution\"},\"address\":{\"street\":\"grand station\",\"city\":\"salt lake\"}}"
}
]
这是我的模型类:
用户.dart
import 'package:json_annotation/json_annotation.dart';
import 'details.dart';
part 'user.g.dart';
@JsonSerializable(explicitToJson: true)
class User {
User(this.name, this.surname, this.details);
String name;
String surname;
Details details;
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
用户.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'user.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
User _$UserFromJson(Map<String, dynamic> json) {
return User(
json['name'] as String,
json['surname'] as String,
json['details'] == null
? null
: Details.fromJson(json['details'] as Map<String, dynamic>),
);
}
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
'name': instance.name,
'surname': instance.surname,
'details': instance.details?.toJson(),
};
细节.dart
import 'package:json_annotation/json_annotation.dart';
import 'address.dart';
import 'work.dart';
part 'details.g.dart';
@JsonSerializable(explicitToJson: true)
class Details {
Details(this.work, this.address);
Work work;
Address address;
factory Details.fromJson(Map<String, dynamic> json) =>
_$DetailsFromJson(json);
Map<String, dynamic> toJson() => _$DetailsToJson(this);
}
细节.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'details.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Details _$DetailsFromJson(Map<String, dynamic> json) {
return Details(
json['work'] == null
? null
: Work.fromJson(json['work'] as Map<String, dynamic>),
json['address'] == null
? null
: Address.fromJson(json['address'] as Map<String, dynamic>),
);
}
Map<String, dynamic> _$DetailsToJson(Details instance) => <String, dynamic>{
'work': instance.work?.toJson(),
'address': instance.address?.toJson(),
};
工作.dart
import 'package:json_annotation/json_annotation.dart';
part 'work.g.dart';
@JsonSerializable(explicitToJson: true)
class Work {
Work(this.salary, this.company);
String salary;
String company;
factory Work.fromJson(Map<String, dynamic> json) => _$WorkFromJson(json);
Map<String, dynamic> toJson() => _$WorkToJson(this);
}
工作.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'work.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Work _$WorkFromJson(Map<String, dynamic> json) {
return Work(
json['salary'] as String,
json['company'] as String,
);
}
Map<String, dynamic> _$WorkToJson(Work instance) => <String, dynamic>{
'salary': instance.salary,
'company': instance.company,
};
地址.dart
import 'package:json_annotation/json_annotation.dart';
part 'address.g.dart';
@JsonSerializable(explicitToJson: true)
class Address {
Address(this.street, this.city);
String street;
String city;
factory Address.fromJson(Map<String, dynamic> json) =>
_$AddressFromJson(json);
Map<String, dynamic> toJson() => _$AddressToJson(this);
}
地址.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'address.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Address _$AddressFromJson(Map<String, dynamic> json) {
return Address(
json['street'] as String,
json['city'] as String,
);
}
Map<String, dynamic> _$AddressToJson(Address instance) => <String, dynamic>{
'street': instance.street,
'city': instance.city,
};
最后,这里有应用程序:main.dart
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'user.dart';
import 'details.dart';
import 'address.dart';
import 'work.dart';
import 'package:built_value/serializer.dart';
import 'dart:convert' as json;
import 'package:meta/meta.dart';
import 'package:built_value/built_value.dart';
import 'package:built_collection/built_collection.dart';
import 'dart:developer';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Future<List<User>> getUsers() async {
var url = "empty for now"; // here there will be the request now I' m using fake data
//final response = await http.get(url);
//final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
String data = r'''[
{
"name": "260",
"surname": "430011",
"areaName": "Camera1-Zone1",
"details": "{\"work\":{\"salary\":\"116\",\"company\":\"evolution\"},\"address\":{\"street\":\"grand station\",\"city\":\"salt lake\"}}"
},
{
"name": "260",
"surname": "430011",
"areaName": "Camera1-Zone1",
"details": "{\"work\":{\"salary\":\"116\",\"company\":\"evolution\"},\"address\":{\"street\":\"grand station\",\"city\":\"salt lake\"}}"
}
]''';
final parsed = json.jsonDecode(data).cast<Map<String, dynamic>>();
return parsed.map<User>((json) {
return User.fromJson(json);
}).toList();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("List"),
backgroundColor: Colors.blue,
),
body: Container(
child: FutureBuilder<List<User>>(
future: getUsers(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, int index) {
return ListTile(
title: Text(snapshot.data[index].name),
subtitle: Text(snapshot.data[index].surname));
},
);
} else if (snapshot.hasError) {
return Center(
child: Text(snapshot.error.toString()),
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),
),
),
);
}
}
你能帮我解决这个错误并显示所有嵌套数据吗?谢谢!
感谢您的帮助!