Farhan Fida
Farhan Fida

Reputation: 180

Flutter json.decode() sometimes works and sometimes doesnt while parsing the same object

I'm new to flutter and was working with json. when I am decoding the response I got from the server by using json.decode() I sometimes get the following error

flutter: FormatException: Unexpected character (at character 21)

sometimes it works perfectly.

this is my code

try {
    Map<String, dynamic> map = new Map<String, dynamic>.from(
        json.decode(contents));
    if (map["CompletedJobPackages"] != null) {
      DataStream.compleatedJobspackage =
          DataStream.parseCompletedJobs(map["CompletedJobPackages"]);
      print(map["CompletedJobPackages"]);
      compleatedJobs = DataStream.compleatedJobspackage;
    }
    CompletedJobloaded = true;
  }
  catch(e){
    print(e);
    ToastUtils.showCustomToast(context, "An Error Occured. Try Again !", false);

  }

this is the object I'm trying to decode

{
            "CompletedJob": {
                "CompletedJobID": 7,
                "DriverID": 34,
                "JobNumber": "80252C20",
                "TraderID": 7,
                "TripType": "Two Way",
                "CargoType": "wd",
                "CargoWeight": 230,
                "LoadingPlace": "dc",
                "UnloadingPlace": "sd",
                "LoadingDate": "2020-05-25",
                "LoadingTime": "12:59:00",
                "EntryExit": 1,
                "AcceptedDelay": 4,
                "Price": 34,
                "Created": "2020-05-23T04:22:10.000Z"
            },
            "BillPaid": 0,
            "DriverReview": {
                "DriverReviewID": 11,
                "DriverID": 34,
                "TraderID": 7,
                "CompletedJobID": 7,
                "Rating": 100,
                "Review": "dscsdc",
                "Created": "2020-05-28"
            }
        },

Upvotes: 5

Views: 4295

Answers (2)

Sundbox
Sundbox

Reputation: 81

Definitely the problem is the emulator, after several days looking for the problem I found this post and I have verified that it does not fail on my real phone.

Different emulators fails different number of times (maybe something related to the ram??).

Also consider using compute(jsonDecode, response.body) to decode the string as indicated in Parse JSON in the background.

compute fails less times on emulators, but still failing sometimes. Doesn't fails in real phone.

Upvotes: 1

Farhan Fida
Farhan Fida

Reputation: 180

Okay so after doing a little research I realized the problem. the HTTP library I was using dart:io was not returning the complete JSON string in the response thus their was a problem in converting it into a JSON object

I just used

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

   Map<String, String> requestHeaders = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
      'Authorization':"JWT "+DataStream.token
    };
    final response = await http.get(URLs.getCompletedJobPackagesURL(), headers:requestHeaders);

    if (response.statusCode == 200) {

      var jsonResponse = convert.jsonDecode(response.body);

      print(jsonResponse);

      Map<String, dynamic> map = convert.jsonDecode(response.body);

       if(map["CompletedJobPackages"]!= null) {
         DataStream.compleatedJobspackage =
             DataStream.parseCompletedJobs(map["CompletedJobPackages"]);
         compleatedJobs = DataStream.compleatedJobspackage;

       }
  
       setState(() {
       });

    }

instead of

import 'dart:io';

final client = HttpClient();
try{
final request = await client.getUrl(Uri.parse(URLs.getDrivingLicenceURL()));
request.headers.set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
request.headers.add("Authorization", "JWT "+DataStream.token);
final response = await request.close();

response.transform(utf8.decoder).listen((contents) async {
 // print(response.statusCode);
  Map<String, dynamic> driverMap = jsonDecode(contents) as Map<String, dynamic>;
  isloadlicence = true;

  if(driverMap["CompletedJobPackages"]!= null) {
    DataStream.compleatedJobspackage =
    new DrivingLicence.fromJson(driverMap["CompletedJobPackages"]);

  }
  setState(() {

  });
});


 }catch(e){

  print(e);
  ToastUtils.showCustomToast(context, "An Error Occurred. Try Again !", false);
  //pr.hide();

  }

Upvotes: 2

Related Questions