Flutter: SyntaxError: Unexpected token < in JSON at position 0

4,080

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

Main:

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

Result:

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})
Share:
4,080
Admin
Author by

Admin

Updated on December 27, 2022

Comments

  • Admin
    Admin over 1 year

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

    Code:

        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());
        }
      }
    
    • Andrej
      Andrej about 3 years
      You got the error because your api returned html not json.
  • Altimus Prime
    Altimus Prime about 3 years
    Please include some explanation with your answer.
  • Admin
    Admin about 3 years
    I created a new project just with your code This appears: 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:9‌​1:40) at main$.next (<anonymous>) ....
  • Ουιλιαμ Αρκευα
    Ουιλιαμ Αρκευα about 3 years
    This seems to be an error from your configuration. (1) Check if you can get response from http://iot.productio.net/api/Measurement/GetMeasurements in your browser, (2) What's your system info?, (3) Have you checked this post?
  • Admin
    Admin about 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.