从API获取数据时,我遇到了一个错误,如果颤抖,我应该如何获取数据?

发布于 2025-02-10 06:19:23 字数 986 浏览 2 评论 0原文

我使用模型从api获取数据。但是,我遇到了一个问题,即当我获得'Gallery'数据时,我会遇到一个错误,也就是说,我得到了错误的数据。我需要获取'gallery'字段,并在其内部使用'url'字段 - 照片的链接,以便将来使用它。您能告诉我如何正确获取'url'字段?

{
    "data": {
        "id": 35,
        "picture_url": null,
        "email_confirmed": false,
        "gallery": [
            {
                "url": "https://picture-staging.s3.eu-central.jpeg",
                "mime_type": "image/jpeg",
                "type": "gallery",
                "updated_at": "2022",
                "created_at": "2022"
            }
        ],
        "updated_at": "2022",
        "created_at": "2022"
    }
}

模型

class User {
  final int id;
  List? gallery;

  User({
    required this.id,
    this.gallery,
  });

  User.fromJson(Map<String, dynamic> json)
      : this(
          id: json['id'] as int,
          gallery: json['gallery']['url'],
        );

I am getting data from an API using a model. But I ran into a problem that when I get the 'gallery' data, I get an error, that is, I get the data incorrectly. I need to get the 'gallery' field and inside it take the 'url' field - a link to the photo, in order to use it in the future. Can you tell me how to get the 'url' field correctly?

{
    "data": {
        "id": 35,
        "picture_url": null,
        "email_confirmed": false,
        "gallery": [
            {
                "url": "https://picture-staging.s3.eu-central.jpeg",
                "mime_type": "image/jpeg",
                "type": "gallery",
                "updated_at": "2022",
                "created_at": "2022"
            }
        ],
        "updated_at": "2022",
        "created_at": "2022"
    }
}

model

class User {
  final int id;
  List? gallery;

  User({
    required this.id,
    this.gallery,
  });

  User.fromJson(Map<String, dynamic> json)
      : this(
          id: json['id'] as int,
          gallery: json['gallery']['url'],
        );

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无所的.畏惧 2025-02-17 06:19:23

在您的API响应中,有一个画廊对象列表,因此您必须穿越所有内容。

User.fromJson(Map<String, dynamic> json) {
    json = json['data'];
    id = json['id'];
    pictureUrl = json['picture_url'];
    emailConfirmed = json['email_confirmed'];
    if (json['gallery'] != null) {
      gallery = <Gallery>[];
      json['gallery'].forEach((v) {
        gallery!.add(new Gallery.fromJson(v));
      });
    }
    updatedAt = json['updated_at'];
    createdAt = json['created_at'];
  }

有多种工具可以帮助您创建该.fromjson方法,例如 this 。在那里粘贴您的JSON,它将为您生成Dart代码,真的对我有帮助。

用法应该这样:

User user = User.fromJson(yourApiResponseJson);
print(user.id);
print(user.gallery); //prints entire list of gallery
print(user.gallery.first.url); //prints only first object url

In your API response, there is a list of gallery objects therefore you have to traverse through all of them.

User.fromJson(Map<String, dynamic> json) {
    json = json['data'];
    id = json['id'];
    pictureUrl = json['picture_url'];
    emailConfirmed = json['email_confirmed'];
    if (json['gallery'] != null) {
      gallery = <Gallery>[];
      json['gallery'].forEach((v) {
        gallery!.add(new Gallery.fromJson(v));
      });
    }
    updatedAt = json['updated_at'];
    createdAt = json['created_at'];
  }

There are multiple tools that helps you create that .fromJson method, like this. Paste your json there and it will generate dart code for you, really helps me.

The usage should like this:

User user = User.fromJson(yourApiResponseJson);
print(user.id);
print(user.gallery); //prints entire list of gallery
print(user.gallery.first.url); //prints only first object url
一生独一 2025-02-17 06:19:23

我希望这不是您的整个模型,因为该模型无法访问“数据” json响应中的密钥,您的模型应开始获取键data然后传递对于在这种情况下应命名用户的另一个类

,这是一个简短的示例

class User {
    User({
        required this.data,
    });

    final Data data;

    factory User.fromJson(Map<String, dynamic> json) => User(
        data: Data.fromJson(json["data"]),
    );
}

data类可能是这样的:

class Data {
    Data({
        required this.id,
        required this.pictureUrl,
        required this.emailConfirmed,
        required this.gallery,
        required this.updatedAt,
        required this.createdAt,
    });

    final int id;
    final dynamic pictureUrl;
    final bool emailConfirmed;
    final List<Gallery> gallery;
    final String updatedAt;
    final String createdAt;

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        id: json["id"],
        pictureUrl: json["picture_url"],
        emailConfirmed: json["email_confirmed"],
        gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
        updatedAt: json["updated_at"],
        createdAt: json["created_at"],
    );
    
}

我建议您使用 quickType

I hope that is not your whole model, because that model is not accessing the "data" key on the json response, your model should start getting the key data then pass it to another class that in this case should be named User

here is a brief example

class User {
    User({
        required this.data,
    });

    final Data data;

    factory User.fromJson(Map<String, dynamic> json) => User(
        data: Data.fromJson(json["data"]),
    );
}

The Data class could be like this:

class Data {
    Data({
        required this.id,
        required this.pictureUrl,
        required this.emailConfirmed,
        required this.gallery,
        required this.updatedAt,
        required this.createdAt,
    });

    final int id;
    final dynamic pictureUrl;
    final bool emailConfirmed;
    final List<Gallery> gallery;
    final String updatedAt;
    final String createdAt;

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        id: json["id"],
        pictureUrl: json["picture_url"],
        emailConfirmed: json["email_confirmed"],
        gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
        updatedAt: json["updated_at"],
        createdAt: json["created_at"],
    );
    
}

I reccomend you using Quicktype

⒈起吃苦の倖褔 2025-02-17 06:19:23

嘿,您可以使用工具从JSON生成DART模型。

以下是从上方生成的代码

// final user = userFromJson(jsonString);
import 'dart:convert';

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

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

class User {
  User({
    required this.data,
  });

  Data data;

  factory User.fromJson(Map<String, dynamic> json) => User(
    data: Data.fromJson(json["data"]),
  );

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

class Data {
  Data({
    this.id,
    this.pictureUrl,
    this.emailConfirmed,
    this.gallery,
    this.updatedAt,
    this.createdAt,
  });

  int? id;
  String? pictureUrl;
  bool? emailConfirmed;
  List<Gallery>? gallery;
  String? updatedAt;
  String? createdAt;

  factory Data.fromJson(Map<String, dynamic> json) => Data(
    id: json["id"],
    pictureUrl: json["picture_url"],
    emailConfirmed: json["email_confirmed"],
    gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
    updatedAt: json["updated_at"],
    createdAt: json["created_at"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "picture_url": pictureUrl,
    "email_confirmed": emailConfirmed,
    "gallery": List<dynamic>.from(gallery.map((x) => x.toJson())),
    "updated_at": updatedAt,
    "created_at": createdAt,
  };
}

class Gallery {
  Gallery({
    this.url,
    this.mimeType,
    this.type,
    this.updatedAt,
    this.createdAt,
  });

  String? url;
  String? mimeType;
  String? type;
  String? updatedAt;
  String? createdAt;

  factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
    url: json["url"],
    mimeType: json["mime_type"],
    type: json["type"],
    updatedAt: json["updated_at"],
    createdAt: json["created_at"],
  );

  Map<String, dynamic> toJson() => {
    "url": url,
    "mime_type": mimeType,
    "type": type,
    "updated_at": updatedAt,
    "created_at": createdAt,
  };
}

//您可以这样使用

 final user = userFromJson(jsonString);
 String? url =  user.data?.gallery?.url;

Hey you can use this tool to generate your dart model from json.

Below is generated code from above tool

// final user = userFromJson(jsonString);
import 'dart:convert';

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

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

class User {
  User({
    required this.data,
  });

  Data data;

  factory User.fromJson(Map<String, dynamic> json) => User(
    data: Data.fromJson(json["data"]),
  );

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

class Data {
  Data({
    this.id,
    this.pictureUrl,
    this.emailConfirmed,
    this.gallery,
    this.updatedAt,
    this.createdAt,
  });

  int? id;
  String? pictureUrl;
  bool? emailConfirmed;
  List<Gallery>? gallery;
  String? updatedAt;
  String? createdAt;

  factory Data.fromJson(Map<String, dynamic> json) => Data(
    id: json["id"],
    pictureUrl: json["picture_url"],
    emailConfirmed: json["email_confirmed"],
    gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
    updatedAt: json["updated_at"],
    createdAt: json["created_at"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "picture_url": pictureUrl,
    "email_confirmed": emailConfirmed,
    "gallery": List<dynamic>.from(gallery.map((x) => x.toJson())),
    "updated_at": updatedAt,
    "created_at": createdAt,
  };
}

class Gallery {
  Gallery({
    this.url,
    this.mimeType,
    this.type,
    this.updatedAt,
    this.createdAt,
  });

  String? url;
  String? mimeType;
  String? type;
  String? updatedAt;
  String? createdAt;

  factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
    url: json["url"],
    mimeType: json["mime_type"],
    type: json["type"],
    updatedAt: json["updated_at"],
    createdAt: json["created_at"],
  );

  Map<String, dynamic> toJson() => {
    "url": url,
    "mime_type": mimeType,
    "type": type,
    "updated_at": updatedAt,
    "created_at": createdAt,
  };
}

// You can use like this

 final user = userFromJson(jsonString);
 String? url =  user.data?.gallery?.url;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文