如何从Dart http调用返回json /如何完全消耗流? [英] How to return a json from a Dart http call / How to consume a stream entirely?
问题描述
这是我的代码,应该返回一个json。我从这里 https://github.com/flutter/flutter/issues/15110
Here's my code that should return a json. I adapted this code from here https://github.com/flutter/flutter/issues/15110
Stream _defaultReturn(HttpClientResponse httpClientResponse) {
Stream response = httpClientResponse.
transform(utf8.decoder).
transform(json.decoder).
asyncMap((json) => jsonDecode(json));
return response;
}
Future<dynamic> get(String endpoint) async {
HttpClientRequest httpClientRequest =
await httpClient.getUrl(Uri.parse(_url + endpoint));
_addCookies(httpClientRequest);
final HttpClientResponse httpClientResponse =
await httpClientRequest.close();
return _defaultReturn(httpClientResponse);
}
我将返回类型为 Stream
放入 _defaultReturn
,因为intellisense告诉我,巨大的东西使我返回了 Stream
。我实际上想接收一个json(应该是地图)。我想我会消耗或订阅此流以获得有用的东西。但是,我认为parsin json作为流不是有用的。解析之前,我不需要整个json吗?
I've put a return type of Stream
into _defaultReturn
because intellisense told me that giant thing returned me a Stream
. I would actually want to receive a json (which should be a map). I think I migth consume or subscribe to this stream to get something useful. However, I don't see parsin json as stream as being useful. Don't I need the entire json before parsing? Shouldn't I simply accumulate everything into a String
and then simply call jsonDecode
?
哪个是从http调用返回json的最有效方法?以及如何做?
Which is the most efficient way of returning a json from an http call? And how to do it?
推荐答案
json.decoder
将侦听源代码流,并且始终将其内容转换为一个 对象
,因此您只需将其与流的<$ c $一起返回即可c> .first :
json.decoder
will listen source stream and always transform its content to just one Object
, so you can just return it with stream's .first
:
Future<Object> get(String endpoint) async {
var httpClientRequest = await httpClient.getUrl(Uri.parse(_url + endpoint));
_addCookies(httpClientRequest);
final httpClientResponse = await httpClientRequest.close();
return httpClientResponse
.transform(utf8.decoder)
.transform(json.decoder)
.first;
}
然后您可以像这样使用它:
Then you can use it like this:
var jsonObject = await myHttpClient.get(myEndpoint);
这篇关于如何从Dart http调用返回json /如何完全消耗流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!