【问题标题】:Is it possible to read JSON response partially from REST api with Dart是否可以使用 Dart 从 REST api 部分读取 JSON 响应
【发布时间】:2019-05-07 16:56:50
【问题描述】:

是否可以使用 Dart 流式传输 REST API JSON 响应? 前任。响应大小为 5000 行。我想逐行阅读,而无需先从源代码加载整个响应。

我认为 Java 和 JavaScript 可以实现类似的功能。

【问题讨论】:

    标签: json api parsing dart stream


    【解决方案1】:

    使用http 包,您可以使用send() 方法发送请求并在响应中使用Stream。

    使用来自dart:convert 的Utf8Decoder 和LineSplitter,您可以在收到每一行时对其进行解码和读取。

    import 'dart:convert';
    import 'package:http/http.dart';
    
    main() async {
      var request = Request('GET', Uri.parse('http://localhost:8090'));
      var response = await request.send();
    
      var lineStream =
          response.stream.transform(Utf8Decoder()).transform(LineSplitter());
    
      // lineStream is a Stream<String> with each line from the response as an event.
      // We can use the listen() method or await for to read it.
    
      await for (String line in lineStream) {
        print(line);
      }
    }
    

    【讨论】:

    • +1 如果我理解正确,这不会首先下载整个 json 响应,而只会逐步下载?
    • 是的,它应该在下载这些行时触发它们,而不是等待整个文件完成。
    猜你喜欢
    • 2020-09-28
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    相关资源
    最近更新 更多