Home > other >  Flutter jsonDecode returns String instead of List
Flutter jsonDecode returns String instead of List

Time:08-28

I want to decode my json to a List but jsonDecode returns String instead of List.

My JSON:

[{
    "TicketID": 31,
    "EmpID": "11553",
    "Name": "Test",
    "Location": null,
    "PhoneExt": 345345,
    "Code": null,
    "Reason": null,
    "Category": null,
    "Created": null,
    "Username": "abc",
    "OtherLocation": null,
    "Room": null,
    "Floor": null,
    "CodeBlueDone": null,
    "CodeBlueDoneDate": null,
    "LocationCode": null,
    "PatientType": null,
    "EmergencyType": "Emergency",
    "FilledDateTime": null,
    "SubmitDateTime": null,
    "Type": null,
    "CallTime": "2022-08-26T13:43:25.003",
    "Status": "New"
}, {
    "TicketID": 30,
    "EmpID": "12",
    "Name": "dbdb",
    "Location": null,
    "PhoneExt": 123,
    "Code": null,
    "Reason": null,
    "Category": null,
    "Created": null,
    "Username": "abc",
    "OtherLocation": null,
    "Room": null,
    "Floor": null,
    "CodeBlueDone": null,
    "CodeBlueDoneDate": null,
    "LocationCode": null,
    "PatientType": null,
    "EmergencyType": "Emergency",
    "FilledDateTime": null,
    "SubmitDateTime": null,
    "Type": null,
    "CallTime": "2022-08-25T21:14:39.807",
    "Status": "New"
}]
if (response.statusCode == 200) {
  jsonDecode(response.body);
  print(jsonDecode(response.body).runtimeType);
}
Future<List> _getDataFromWeb() async {
  try {
    await http.post(
      Uri.parse(apiURL),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
    ).then((response) {
      if (response.statusCode == 200) {
        try {
          final resp = jsonDecode(response.body) as List?;
          print(resp.runtimeType);
        } catch (ex) {
          print("_getDataFromWeb() error: ${ex}");
        }
      } else if (response.statusCode == 404) {
        print("Error 404: ${response.statusCode}");
      } else {
        print("Error: ${response.statusCode}");
      }
    }).catchError((error) {
      print("Error: "   error);
    });
  } catch (ex) {
    print("API-ERR: $ex");
  }
}

Full code to decode is given above

Why the flutter jsonDecode or json.Decode doesn't return a List from above JSON?

EDIT

Calling jsonDecode two times works and returns List

final resp = jsonDecode(jsonDecode(response.body));
print(resp.runtimeType);

I wonder why calling jsonDecode() two times is needed?

CodePudding user response:

Try like this

 final response = jsonDecode(response.body) as List?;
 print(response.runtimeType);

CodePudding user response:

Try this code via QuickType

// To parse this JSON data, do
//
//     final model = modelFromJson(jsonString);

import 'dart:convert';

List<Model> modelFromJson(String str) => List<Model>.from(json.decode(str).map((x) => Model.fromJson(x)));

String modelToJson(List<Model> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Model {
    Model({
        this.ticketId,
        this.empId,
        this.name,
        this.location,
        this.phoneExt,
        this.code,
        this.reason,
        this.category,
        this.created,
        this.username,
        this.otherLocation,
        this.room,
        this.floor,
        this.codeBlueDone,
        this.codeBlueDoneDate,
        this.locationCode,
        this.patientType,
        this.emergencyType,
        this.filledDateTime,
        this.submitDateTime,
        this.type,
        this.callTime,
        this.status,
    });

    int ticketId;
    String empId;
    String name;
    dynamic location;
    int phoneExt;
    dynamic code;
    dynamic reason;
    dynamic category;
    dynamic created;
    String username;
    dynamic otherLocation;
    dynamic room;
    dynamic floor;
    dynamic codeBlueDone;
    dynamic codeBlueDoneDate;
    dynamic locationCode;
    dynamic patientType;
    String emergencyType;
    dynamic filledDateTime;
    dynamic submitDateTime;
    dynamic type;
    DateTime callTime;
    String status;

    factory Model.fromJson(Map<String, dynamic> json) => Model(
        ticketId: json["TicketID"],
        empId: json["EmpID"],
        name: json["Name"],
        location: json["Location"],
        phoneExt: json["PhoneExt"],
        code: json["Code"],
        reason: json["Reason"],
        category: json["Category"],
        created: json["Created"],
        username: json["Username"],
        otherLocation: json["OtherLocation"],
        room: json["Room"],
        floor: json["Floor"],
        codeBlueDone: json["CodeBlueDone"],
        codeBlueDoneDate: json["CodeBlueDoneDate"],
        locationCode: json["LocationCode"],
        patientType: json["PatientType"],
        emergencyType: json["EmergencyType"],
        filledDateTime: json["FilledDateTime"],
        submitDateTime: json["SubmitDateTime"],
        type: json["Type"],
        callTime: DateTime.parse(json["CallTime"]),
        status: json["Status"],
    );

    Map<String, dynamic> toJson() => {
        "TicketID": ticketId,
        "EmpID": empId,
        "Name": name,
        "Location": location,
        "PhoneExt": phoneExt,
        "Code": code,
        "Reason": reason,
        "Category": category,
        "Created": created,
        "Username": username,
        "OtherLocation": otherLocation,
        "Room": room,
        "Floor": floor,
        "CodeBlueDone": codeBlueDone,
        "CodeBlueDoneDate": codeBlueDoneDate,
        "LocationCode": locationCode,
        "PatientType": patientType,
        "EmergencyType": emergencyType,
        "FilledDateTime": filledDateTime,
        "SubmitDateTime": submitDateTime,
        "Type": type,
        "CallTime": callTime.toIso8601String(),
        "Status": status,
    };
}

CodePudding user response:

Make sure response.body is in correct type and format. And try decoding via this code:


    final List<dynamic> decodedResponseBody = jsonDecode(response.body);

resource: https://api.flutter.dev/flutter/dart-convert/jsonDecode.html

CodePudding user response:

Try

json.decode(response.body) as List;

EDIT

Try this format

Future<List> _getDataFromWeb() async {
  try {
    var response = await http.post(
      Uri.parse(apiURL),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
    );

      if (response.statusCode == 200) {
        try {
          final resp = json.decode(response.body.toString()) as List?;
          print(resp.runtimeType);
        } catch (ex) {
          print("_getDataFromWeb() error: ${ex}");
        }
      } else if (response.statusCode == 404) {
        print("Error 404: ${response.statusCode}");
      } else {
        print("Error: ${response.statusCode}");
      }
    }
  } catch (ex) {
    print("API-ERR: $ex");
  }
}

CodePudding user response:

Calling jsonDecode two times works and returns List

final resp = jsonDecode(jsonDecode(response.body));
print(resp.runtimeType);

Finally found the answer after investing hours into it.

  • Related