【问题标题】:Flutter: SyntaxError: Unexpected token < in JSON at position 0Flutter:SyntaxError:位置0的JSON中的意外标记<
【发布时间】:2021-05-21 19:36:21
【问题描述】:

我需要从 API 获取数据,但我的 try-catch 失败并出现 SyntaxError: Unexpected token

代码:

    String problems;
     try {
         final response = await http.get('http://myURL',headers: {"Accept": "application/json"});
      log("after http");
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        problems = data["IsSuccess"];
        return problems.toString();
      } else {
        throw Exception('Failed to load status data');
      }
    } catch (exc) {
      log("catch:" + exc.toString());
    }
  }

【问题讨论】:

  • 您收到错误是因为您的 api 返回的是 html 而不是 json。

标签: json api flutter http dart


【解决方案1】:

网络服务:

import 'dart:convert';

import 'package:http/http.dart' as http;


class NetService {
  /* ---------------------------------------------------------------------------- */
  static Future<T> getJson<T>(String url) {
    return http.get(Uri.parse(url))
      .then((response) {
        if (response.statusCode == 200) {
          return jsonDecode(response.body) as T;
        }
        print('Status Code : ${response.statusCode}...');
        return null;
      })
      .catchError((err) => print(err));
  }
}

主要:

import 'dart:async';

import 'package:_samples2/networking.dart';

class IOT {
  List data;

  FutureOr<void> fetchMeasurements() async {
    await NetService.getJson<Map<String, dynamic>>('http://iot.productio.net/api/Measurement/GetMeasurements')
      .then((response) {
        data = (response != null && response['IsSuccess'])
          ? response['Entity']
          : null;
      })
      .whenComplete(() => print('Fetching done!....'));
  }
}
void main(List<String> args) async {
  var iot = IOT();
  await iot.fetchMeasurements();
  print(iot.data.take(3).toString());
}

结果:

Fetching done!....
({Id: 21315, MeasurementDate: 2021-02-18T22:06:20.8365195, Temperature: 20.6, Humidity: 36.8, Misto: loznice}, {Id: 21314, MeasurementDate: 2021-02-18T22:01:19.1337516, Temperature: 20.6, Humidity: 37.0, Misto: loznice}, {Id: 21313, MeasurementDate: 2021-02-18T21:56:18.1720883, Temperature: 20.6, Humidity: 36.9, Misto: loznice})

【讨论】:

  • 请在您的回答中附上一些解释。
  • 我用你的代码创建了一个新项目 出现:Restarted application in 11 308ms. XMLHttpRequest error. Fetching done!.... TypeError: Cannot read property 'Symbol(dartx.take)' of null at main$ (http://localhost:54159/packages/jsontest/main.dart.lib.js:91:40) at main$.next (&lt;anonymous&gt;) ....
  • 这似乎是您的配置错误。 (1) 检查您是否可以在浏览器中收到来自http://iot.productio.net/api/Measurement/GetMeasurements 的响应,(2) 您的系统信息是什么?,(3)你检查过这个post吗?
猜你喜欢
  • 2018-03-02
  • 1970-01-01
  • 2020-10-31
  • 2021-10-22
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多