我正在try 从Web服务URL获取一个JSON数组,并在JSON中解析它.问题是,我遵循的教程显示了接收一个json obj并对其进行解析,但我需要知道如何接收JSON数组并对其进行解析.下面是我正在编写的代码,我被卡住了.

Model

class Fact {
  int id;
  int fact_id;
  String fact;
  String image;
  String reference;

  Fact(this.id, this.fact_id, this.fact, this.image, this.reference);

  Fact.fromJson(Map<String, dynamic> json)
    : id = json['id'],
      fact_id = json['fact_id'],
      fact = json['fact'],
      image = json['image'],
      reference = json['reference'];

    Map<String, dynamic> toJson() =>
    {
      'id' : id,
      'fact_id': fact_id,
      'fact': fact,
      'image': image,
      'reference': reference,
    };
}

我不知道如何写这篇文章,因为我从网络服务中获得了大量事实.

Fact Download Manager

class FactsManager {
  var constants = Constants();

  fetchFacts() {
    final lastFactId = 0;
    var fetchRequestUrl = constants.fetch_facts_url;

    if (lastFactId == 0) {
      fetchRequestUrl = fetchRequestUrl + "?count=" + constants.firstTimePostCount.toString();
    } else {
      fetchRequestUrl = fetchRequestUrl + "?count=" + constants.firstTimePostCount.toString() + "&last_id=" + lastFactId.toString();
    }
    Future<List<Fact>> fetchPost() async {
      final response = await http.get(fetchRequestUrl);

      if (response.statusCode == 200) {
        return List<Fact>
      }
    }
  }
}

我正在try 解析的示例数据.

[
    {
        "id": "407",
        "fact": "Monsanto once tried to genetically engineer blue cotton, to produce denim without the use of dyes, reducing the pollution involved in the dyeing process.   ",
        "reference": null,
        "image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact492.png",
        "fact_id": "1"
    },
    {
        "id": "560",
        "fact": "You can count from zero to nine hundred ninety-nine without ever having to use the letter \"a\"   ",
        "reference": null,
        "image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact04.png",
        "fact_id": "2"
    },
    {
        "id": "564",
        "fact": "In order to keep the project a secret, the British army used the innocuous name \"mobile water carriers\" for a motorized weapons project - which is the reason we call them \"tanks\".   ",
        "reference": null,
        "image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact116.png",
        "fact_id": "3"
    },
    {
        "id": "562",
        "fact": "In 2010 the mummified corpse of Sogen Kato, thought to be Tokyo's oldest man, was found in his bedroom by government officials. He had actually died in 1978.   ",
        "reference": null,
        "image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact216.png",
        "fact_id": "4"
    },
    {
        "id": "566",
        "fact": "In 1927 the US Supreme Court ruled it constitutional for the government to forcefully sterilize mentally handicapped people   ",
        "reference": null,
        "image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact316.png",
        "fact_id": "5"
    }
]

推荐答案

您可以执行以下操作:

String receivedJson = "... Your JSON string ....";
List<dynamic> list = json.decode(receivedJson);
Fact fact = Fact.fromJson(list[0]);

在任何情况下,您都必须在您的json字符串和您创建的事实类中考虑以下事项:

  • 在json字符串中,id和faceid是字符串,您将它们视为int.要么更改json类,要么更改事实类.
  • json字符串中的一些字符串会产生错误,因为字符串中有额外的引号,这会混淆解码器.

工程的json字符串如下所示:

String receivedJson = """
[
    {
        "id": 407,
        "fact": "Monsanto once tried to genetically engineer blue cotton, to produce denim without the use of dyes, reducing the pollution involved in the dyeing process.   ",
        "reference": null,
        "image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact492.png",
        "fact_id": 1
    }
]
    """;

Flutter相关问答推荐

为什么我需要等待重新访问Firestore数据库,即使它已经做了之前?

我如何才能收到每天重复的预定通知?

允许冻结在初始化时使用工厂

Fighter:基于ChangeNotifier状态动态更新AppBar中的图标

SupabaseFlutter 集成问题:无法更新行

在 flutter 吧蜂巢中拯救主题

从Firestore流式传输单个文档还是整个集合更好?

谷歌 map 在 flutter 应用程序中显示错误的当前位置

Flutter 需要 Xcode 14 或更高版本

断言失败:std::move(hal_2_1_verifier).Run(). 初始化,LE音频客户端至少需要Bluetooth音频HAL V2.1

Riverpod 2.3.6:AutoDisposeNotifier和ref.onDispose自动处理

如何使Flutter 屏幕无法关闭?

我想在文本结束后显示分隔线.它会在第一行、第二行或第三行结束

Flutter:如何从运行时创建的列表中访问单个子部件的值

在 Flutter 中使用 HardwareKeyboard 时所有键都没有响应

如何在 Flutter 中将列小部件添加到行小部件?

Flutter - 异步文件读取异常处理

Flutter Widget 测试:无法使用 find.byWidget() 找到小部件

构建失败 - 无法解析 io.grpc:grpc-core:[1.28.0]. (是的,我已经升级到 mavenCentral())

为什么这个循环只发生一次?Flutter /dart