Home > Software design >  FormatException: Unexpected character (at character 3) I/flutter (32137) error Flutter
FormatException: Unexpected character (at character 3) I/flutter (32137) error Flutter

Time:06-27

I want to return API data when I do jsonDecode, but I am getting this error: FormatException: Unexpected character (at character 3) I/flutter (32137): [{Id: 0, SourceId: 0, ServiceId: 11, CategoryId: 5, Category: Valuation, De...

My response.data return a valid json but when I want to decode, I get that error, can anyone please help.

My code is below:

Future<Autogenerated?>? signInData() async {
    final prefs = await SharedPreferences.getInstance();
    final String? token = prefs.getString('token');

    try {
      Response response = await _dio.post('$_baseUrl/api/gateway',
          data: {
            "ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
            "PlatformId": "ios",
            "ClientUserId": "AhmedOmar",
            "VinNumber": VINumber
          },
          options: Options(
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
              "Charset": 'utf-8',
              "Authorization": "Bearer $token",
            },
          ));
      print("data is here");
      print(response.data.toString());
      print(response.statusCode);
      if (response.statusCode == 200) {
        print("decoded");
        print(Autogenerated.fromJson(jsonDecode(response.data.toString())));
        return Autogenerated.fromJson(jsonDecode(response.data.toString()));
      } else if (response.statusCode == 500) {
        // call your refresh token api here and save it in shared preference
        print(response.statusCode);
        await getToken();
        signInData();
      } else {
        throw Exception('Failed to load data');
      }
    } catch (e) {
      print(e);
    }
    //  return null;
  }

My Autogenerated model

class Autogenerated {
  int? id;
  int? sourceId;
  int? serviceId;
  int? categoryId;
  String? category;
  String? description;
  int? serviceResponsePropertyId;
  int? mappingId;
  bool? isVisible;
  int? packageRequestId;
  int? sortOrder;
  Value? value;

  Autogenerated(
      {this.id,
      this.sourceId,
      this.serviceId,
      this.categoryId,
      this.category,
      this.description,
      this.serviceResponsePropertyId,
      this.mappingId,
      this.isVisible,
      this.packageRequestId,
      this.sortOrder,
      this.value});

  Autogenerated.fromJson(Map<String, dynamic> json) {
    id = json['Id'];
    sourceId = json['SourceId'];
    serviceId = json['ServiceId'];
    categoryId = json['CategoryId'];
    category = json['Category'];
    description = json['Description'];
    serviceResponsePropertyId = json['ServiceResponsePropertyId'];
    mappingId = json['MappingId'];
    isVisible = json['IsVisible'];
    packageRequestId = json['PackageRequestId'];
    sortOrder = json['SortOrder'];
    value = json['Value'] != null ? new Value.fromJson(json['Value']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['Id'] = this.id;
    data['SourceId'] = this.sourceId;
    data['ServiceId'] = this.serviceId;
    data['CategoryId'] = this.categoryId;
    data['Category'] = this.category;
    data['Description'] = this.description;
    data['ServiceResponsePropertyId'] = this.serviceResponsePropertyId;
    data['MappingId'] = this.mappingId;
    data['IsVisible'] = this.isVisible;
    data['PackageRequestId'] = this.packageRequestId;
    data['SortOrder'] = this.sortOrder;
    if (this.value != null) {
      data['Value'] = this.value!.toJson();
    }
    return data;
  }
}

class Value {
  String? make;
  String? type;
  String? model;
  int? year;
  String? body;
  String? driveType;
  String? fueType;

  Value(
      {this.make,
      this.type,
      this.model,
      this.year,
      this.body,
      this.driveType,
      this.fueType});

  Value.fromJson(Map<String, dynamic> json) {
    make = json['make'];
    type = json['type'];
    model = json['model'];
    year = json['year'];
    body = json['body'];
    driveType = json['drive_type'];
    fueType = json['fue_type'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['make'] = this.make;
    data['type'] = this.type;
    data['model'] = this.model;
    data['year'] = this.year;
    data['body'] = this.body;
    data['drive_type'] = this.driveType;
    data['fue_type'] = this.fueType;
    return data;
  }
}

My response.data response in console:

[{Id: 0, SourceId: 0, ServiceId: 11, CategoryId: 5, Category: Valuation, Description: AdjustedValues, Value: [], 
ServiceResponsePropertyId: 474, MappingId: 0, IsVisible: true, PackageRequestId: 13853137, SortOrder: 1}, {Id: 0, SourceId: 0, ServiceId: 11, CategoryId: 1, Category: General, Description: ServiceStatus, Value: {StatusCode: 1, StatusDescription: Ok, StatusDetail: 
, RestServiceStatus: null, ServiceResource: null}, ServiceResponsePropertyId: 475, MappingId: 0, IsVisible: false, PackageRequestId: 13853137, SortOrder: 1}, {Id: 0, SourceId: 0, ServiceId: 6, CategoryId: 1, Category: General, Description: CarId, Value: 120354, ServiceResponsePropertyId: 100, MappingId: 0, IsVisible: false, PackageRequestId: 13853137, SortOrder: 1}, {Id: 0, SourceId: 0, ServiceId: 6, CategoryId: 1, Category: General, Description: Year, Value: 2017, ServiceResponsePropertyId: 103, MappingId: 0, IsVisible: true, PackageRequestId: 13853137, SortOrder: 6}, {Id: 0, SourceId: 0, ServiceId: 6, CategoryId: 1, Category: General, D

I don't get why it is printing this, because on postman, it is returning a valid json.

The error appears on this line

 return Autogenerated.fromJson(jsonDecode(response.data.toString()));

CodePudding user response:

Instead of:

return Autogenerated.fromJson(jsonDecode(response.data.toString()));

Try:

return List<Autogenerated>.from(response.data.map((i) => Autogenerated.fromJson(i)));

If this does not work, you should check json serializable package in order to automate the process of creating the fromJson and toJson methods

CodePudding user response:

Hi guys I managed to find a solution to my problem, first I got the error I posted in the question, because my JSON response was invalid so I had to encode my response first, so I did: print(json.encode(response.data)); to get a valid json response.

The second error was type 'List' is not a subtype of type 'Map<String, dynamic>' and I used this link Flutter 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' for assistance, thank you to everyone who helped in the comment.

  • Related