flutter 在Dart中解析JSON时,获取类型“_Map< String,dynamic>”不是类型“String”的子类型错误

x7yiwoj4  于 2023-06-07  发布在  Flutter
关注(0)|答案(2)|浏览(229)

所以我有一个开放的API json响应模型:

{
    "object": "list",
    "data": [
       {
            "id": "whisper-1",
            "object": "model",
            "created": 1677532384,
            "owned_by": "openai-internal",
            "permission": [
                {
                    "id": "modelperm-KlsZlfft3Gma8pI6A8rTnyjs",
                    "object": "model_permission",
                    "created": 1683912666,
                    "allow_create_engine": false,
                    "allow_sampling": true,
                    "allow_logprobs": true,
                    "allow_search_indices": false,
                    "allow_view": true,
                    "allow_fine_tuning": false,
                    "organization": "*",
                    "group": null,
                    "is_blocking": false
                }
            ],
            "root": "whisper-1",
            "parent": null
        },
    ]
 }

下面是数据模型类:

import 'package:flutter_chatgpt/src/data/models/model_model.dart';

class ModelResponse {
  ModelResponse({
    required this.object,
    required this.data,
  });
  late final String object;
  late final List<Model> data;
  
  ModelResponse.fromJson(Map<String, dynamic> json){
    object = json['object'];
    data = List.from(json['data']).map((e)=>Model.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['object'] = object;
    _data['data'] = data.map((e)=>e.toJson()).toList();
    return _data;
  }
}

class Model {
  Model({
    required this.id,
    required this.object,
  });
  late final String id;
  late final String object;
  
  Model.fromJson(Map<String, dynamic> json){
    id = json['id'];
    object = json['object'];
  }

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['id'] = id;
    data['object'] = object;
    return data;
  }
}

但是在API请求时,当我将数据传递给ModelResponse的fromJson()时,我得到了这个错误:

Exception: Failed to fetch models: type '_Map<String, dynamic>' is not a subtype of type 'String'

看起来像是从API获取响应,但函数无法正确解析JSON并将其转换为对象。我不知道是什么引起的。

9o685dep

9o685dep1#

请尝试这个ModelResponse类,基于你的json(从quicktype创建的模型):

import 'dart:convert';

class ModelResponse {
  final String object;
  final List<Datum> data;

  ModelResponse({
    required this.object,
    required this.data,
  });

  factory ModelResponse.fromRawJson(String str) => ModelResponse.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory ModelResponse.fromJson(Map<String, dynamic> json) => ModelResponse(
        object: json["object"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "object": object,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  final String id;
  final String object;
  final int created;
  final String ownedBy;
  final List<Permission> permission;
  final String root;
  final dynamic parent;

  Datum({
    required this.id,
    required this.object,
    required this.created,
    required this.ownedBy,
    required this.permission,
    required this.root,
    required this.parent,
  });

  factory Datum.fromRawJson(String str) => Datum.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        object: json["object"],
        created: json["created"],
        ownedBy: json["owned_by"],
        permission: List<Permission>.from(json["permission"].map((x) => Permission.fromJson(x))),
        root: json["root"],
        parent: json["parent"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "object": object,
        "created": created,
        "owned_by": ownedBy,
        "permission": List<dynamic>.from(permission.map((x) => x.toJson())),
        "root": root,
        "parent": parent,
      };
}

class Permission {
  final String id;
  final String object;
  final int created;
  final bool allowCreateEngine;
  final bool allowSampling;
  final bool allowLogprobs;
  final bool allowSearchIndices;
  final bool allowView;
  final bool allowFineTuning;
  final String organization;
  final dynamic group;
  final bool isBlocking;

  Permission({
    required this.id,
    required this.object,
    required this.created,
    required this.allowCreateEngine,
    required this.allowSampling,
    required this.allowLogprobs,
    required this.allowSearchIndices,
    required this.allowView,
    required this.allowFineTuning,
    required this.organization,
    required this.group,
    required this.isBlocking,
  });

  factory Permission.fromRawJson(String str) => Permission.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Permission.fromJson(Map<String, dynamic> json) => Permission(
        id: json["id"],
        object: json["object"],
        created: json["created"],
        allowCreateEngine: json["allow_create_engine"],
        allowSampling: json["allow_sampling"],
        allowLogprobs: json["allow_logprobs"],
        allowSearchIndices: json["allow_search_indices"],
        allowView: json["allow_view"],
        allowFineTuning: json["allow_fine_tuning"],
        organization: json["organization"],
        group: json["group"],
        isBlocking: json["is_blocking"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "object": object,
        "created": created,
        "allow_create_engine": allowCreateEngine,
        "allow_sampling": allowSampling,
        "allow_logprobs": allowLogprobs,
        "allow_search_indices": allowSearchIndices,
        "allow_view": allowView,
        "allow_fine_tuning": allowFineTuning,
        "organization": organization,
        "group": group,
        "is_blocking": isBlocking,
      };
}

然后用途:

ModelResponse m = ModelResponse.fromRawJson(yourResponseDataAsString);
atmip9wb

atmip9wb2#

将模型类更新为:

class ModelResponse {
  String? object;
  List<PermissionData>? data;

  ModelResponse({this.object, this.data});

  ModelResponse.fromJson(Map<String, dynamic> json) {
    object = json['object'];
    if (json['data'] != null) {
      data = <PermissionData>[];
      json['data'].forEach((v) {
        data!.add(PermissionData.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['object'] = object;
    if (this.data != null) {
      data['data'] = this.data!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class PermissionData {
  String? id;
  String? object;
  int? created;
  String? ownedBy;
  List<Permission>? permission;
  String? root;
  dynamic parent;

  PermissionData(
      {this.id,
      this.object,
      this.created,
      this.ownedBy,
      this.permission,
      this.root,
      this.parent});

  PermissionData.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    object = json['object'];
    created = json['created'];
    ownedBy = json['owned_by'];
    if (json['permission'] != null) {
      permission = <Permission>[];
      json['permission'].forEach((v) {
        permission!.add(Permission.fromJson(v));
      });
    }
    root = json['root'];
    parent = json['parent'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['object'] = object;
    data['created'] = created;
    data['owned_by'] = ownedBy;
    if (permission != null) {
      data['permission'] = permission!.map((v) => v.toJson()).toList();
    }
    data['root'] = root;
    data['parent'] = parent;
    return data;
  }
}

class Permission {
  String? id;
  String? object;
  int? created;
  bool? allowCreateEngine;
  bool? allowSampling;
  bool? allowLogprobs;
  bool? allowSearchIndices;
  bool? allowView;
  bool? allowFineTuning;
  String? organization;
  dynamic group;
  bool? isBlocking;

  Permission(
      {this.id,
      this.object,
      this.created,
      this.allowCreateEngine,
      this.allowSampling,
      this.allowLogprobs,
      this.allowSearchIndices,
      this.allowView,
      this.allowFineTuning,
      this.organization,
      this.group,
      this.isBlocking});

  Permission.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    object = json['object'];
    created = json['created'];
    allowCreateEngine = json['allow_create_engine'];
    allowSampling = json['allow_sampling'];
    allowLogprobs = json['allow_logprobs'];
    allowSearchIndices = json['allow_search_indices'];
    allowView = json['allow_view'];
    allowFineTuning = json['allow_fine_tuning'];
    organization = json['organization'];
    group = json['group'];
    isBlocking = json['is_blocking'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['object'] = object;
    data['created'] = created;
    data['allow_create_engine'] = allowCreateEngine;
    data['allow_sampling'] = allowSampling;
    data['allow_logprobs'] = allowLogprobs;
    data['allow_search_indices'] = allowSearchIndices;
    data['allow_view'] = allowView;
    data['allow_fine_tuning'] = allowFineTuning;
    data['organization'] = organization;
    data['group'] = group;
    data['is_blocking'] = isBlocking;
    return data;
  }
}

然后用途:

ModelResponse.fromJson(yourResponseString);

生成模型类的链接是Json to Dart Model Class

相关问题