Flutter:SyntaxError:意外令牌<在JSON中的位置0 [英] Flutter: SyntaxError: Unexpected token < in JSON at position 0

查看:100
本文介绍了Flutter:SyntaxError:意外令牌<在JSON中的位置0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从API提取数据,但是我的try-catch失败,并出现SyntaxError:Unexpected token<在JSON中的位置0.

I need to fetch data from API but my try-catch fails with SyntaxError: Unexpected token < in JSON at position 0.

代码:

    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());
    }
  }

推荐答案

NetService:

NetService:

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})

这篇关于Flutter:SyntaxError:意外令牌&lt;在JSON中的位置0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆