当前位置: 首页 > 知识库问答 >
问题:

列表视图中的Flutter显示嵌套json返回类型String不是类型强制转换中的Map类型的子类型

白博易
2023-03-14

我要在颤栗中继续我的旅程。我能够在ListView中显示一个简单的json。现在我尝试使用带有嵌套对象的json,但每次运行应用程序时都会出现错误

我正在为json模型类生成代码,如颤振官方文档中建议的那样。

这个错误似乎是在我分析用户时发生的。在调试时,我看到名称和姓氏被成功解析,但当我跳转到user中的details对象时。g、 在行中省道:

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\"}}"    
    }
]

这里有我的模型类:

user.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、 飞镖

// 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(),
    };

细节。飞奔

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);
}

details.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(),
    };

工作飞奔

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、 飞镖

// 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,
    };

住址飞奔

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);
}

address.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(),
              );
            },
          ),
        ),
      ),
    );
  }
}

你能帮我解决这个错误并显示所有嵌套数据吗?谢谢你!

谢谢你的帮助!

共有2个答案

邹高懿
2023-03-14

我找到一个解决办法。

我使用的模型是:

模型飞奔

import 'dart:convert';

List<User> userFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

String userToJson(List<User> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class User {
  User({
    this.name,
    this.surname,
    this.areaName,
    this.details,
  });

  String name;
  String surname;
  String areaName;
  String details;

  factory User.fromJson(Map<String, dynamic> json) => User(
        name: json["name"],
        surname: json["surname"],
        areaName: json["areaName"],
        details: json["details"],
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "surname": surname,
        "areaName": areaName,
        "details": details,
      };
}

Details DetailsFromJson(String str) => Details.fromJson(json.decode(str));

String DetailsToJson(Details data) => json.encode(data.toJson());

class Details {
  Details({
    this.work,
    this.address,
  });

  Work work;
  Address address;

  factory Details.fromJson(Map<String, dynamic> json) => Details(
        work: Work.fromJson(json["work"]),
        address: Address.fromJson(json["address"]),
      );

  Map<String, dynamic> toJson() => {
        "work": work.toJson(),
        "address": address.toJson(),
      };
}

class Address {
  Address({
    this.street,
    this.city,
  });

  String street;
  String city;

  factory Address.fromJson(Map<String, dynamic> json) => Address(
        street: json["street"],
        city: json["city"],
      );

  Map<String, dynamic> toJson() => {
        "street": street,
        "city": city,
      };
}

class Work {
  Work({
    this.salary,
    this.company,
  });

  String salary;
  String company;

  factory Work.fromJson(Map<String, dynamic> json) => Work(
        salary: json["salary"],
        company: json["company"],
      );

  Map<String, dynamic> toJson() => {
        "salary": salary,
        "company": company,
      };
}

主代码是:main。飞奔

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\"}}"
      }
    ]''';
    List<User> users= userFromJson(res);
    return users;
  }

  @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(),
              );
            },
          ),
        ),
      ),
    );
  }
}
彭骏
2023-03-14
 Future<List<User>> getUsers() async {
    var url = "empty for now"; 
   final response = await http.get(url);

     if (response.isEmpty) return null;


    Map<String, dynamic> data = json.decode(response);

    List<dynamic> list = data['data'];

     List<User> result =
     list.map((f) => User.fromJson(f)).toList();

    return result;
  }

如果json数据是这样的--

   {
    "name": "260",
    "surname": "430011",
    "areaName": "Camera1-Zone1",
    "details": {"work":{"salary":"116","company":"evolution"},"address": 
      {"street":"grand station","city":"salt lake"}}
  },

您的模型如下所示:

 import 'dart:convert';
  User userFromJson(String str) => User.fromJson(json.decode(str));

  String userToJson(User data) => json.encode(data.toJson());

 class User {
  User({
    this.name,
    this.surname,
    this.areaName,
    this.details,
 });

String name;
String surname;
String areaName;
Details details;

 factory User.fromJson(Map<String, dynamic> json) => User(
    name: json["name"],
    surname: json["surname"],
    areaName: json["areaName"],
    details: Details.fromJson(json["details"]),
 );

 Map<String, dynamic> toJson() => {
    "name": name,
    "surname": surname,
    "areaName": areaName,
    "details": details.toJson(),
 };
}

class Details {
 Details({
    this.work,
    this.address,
 });

 Work work;
 Address address;

  factory Details.fromJson(Map<String, dynamic> json) => Details(
     work: Work.fromJson(json["work"]),
    address: Address.fromJson(json["address"]),
  );

  Map<String, dynamic> toJson() => {
    "work": work.toJson(),
    "address": address.toJson(),
   };
  }

  class Address {
  Address({
    this.street,
    this.city,
  });

String street;
String city;

factory Address.fromJson(Map<String, dynamic> json) => Address(
    street: json["street"],
    city: json["city"],
);

Map<String, dynamic> toJson() => {
    "street": street,
    "city": city,
  };
 }

class Work {
Work({
    this.salary,
     this.company,
});

String salary;
String company;

 factory Work.fromJson(Map<String, dynamic> json) => Work(
    salary: json["salary"],
    company: json["company"],
 );

  Map<String, dynamic> toJson() => {
    "salary": salary,
     "company": company,
   };
  }

或者如果这样:

   {
    "name": "260",
    "surname": "430011",
    "areaName": "Camera1-Zone1",
    "details": "{\"work\": 
  {\"salary\":\"116\",\"company\":\"evolution\"},\"address\": 
   {\"street\":\"grand station\",\"city\":\"salt lake\"}}"
   }

您的模型如下所示:

import 'dart:convert';

User userFromJson(String str) => User.fromJson(json.decode(str));

String userToJson(User data) => json.encode(data.toJson());

class User {
 User({
    this.name,
    this.surname,
    this.areaName,
    this.details,
});

String name;
String surname;
String areaName;
String details;

factory User.fromJson(Map<String, dynamic> json) => User(
    name: json["name"],
    surname: json["surname"],
    areaName: json["areaName"],
    details: json["details"],
);

Map<String, dynamic> toJson() => {
    "name": name,
    "surname": surname,
    "areaName": areaName,
    "details": details,
 };
}
 类似资料:
  • 当我点击我的颤振应用程序中的一个按钮时,我出现了一个错误。这里有人有解决方案吗?! 路线 争论 还有地图 完全错误 生成CategoryMalsScreen(脏,依赖项:[[U ModalScopeStatus],状态:[U CategoryMalsScreenState]时引发了以下错误:类型“String”不是类型“Map”的子类型 导致错误的相关小部件是:CategoryMalsScreen

  • 我试图创建动态下拉,其值是从使用微服务的查找表之一填充,但我已经尝试了许多方式相同,到目前为止,我还没有成功地使其工作。 下面的代码用于调用webservice 这是我的对象类型 仅用于显示目前运行的以下代码 我做了什么我尝试调用webservice在多种方式调用它,尝试铸造服务响应直接使用JSON字符串响应和可能的事情我尝试过。 你能在这里帮忙吗?我们将不胜感激。

  • 我试图从API获取数据。我得到了错误类型列表不是地图的子类型。我是新来的,不明白我在哪里犯了错误。 这是我的回帖功能: 在我的主屏幕中,我使用了一个,如下所示: 如何解决此错误?提前谢谢。

  • 我试图将一个嵌套的JSON对象发布到API。下面是我正在尝试的简单代码。 我收到错误消息:

  • 我有这个通用函数: 我这样称呼它: 但是,由于我将使用get_存储框作为我的_数据客户端,改为使用配置单元框,因此出现以下错误: 配置单元必须以不同的格式存储数据,这可能是由于加密造成的,但如何解释这一点并消除此错误?

  • 我在尝试使用JSON_serializable序列化从internet获取的复杂JSON并使用FutureProvider将它们连接在一起时遇到了这个问题。这是json文件, 这是包含序列化类的代码, 获取json文件并将其转换为dart的未来提供者, 这是基因编码, 这是转换后的json文件显示的代码 当我试着运行这个项目时,我遇到了这个错误 i/flutter(23347): type'Lis