jsonflutterformatexception

I'm trying to prase the Json data to model class in Flutter. but i'm getting "Flutter FormatException: Unexpected character" Error


My Code :

Future<List<Quections>?> getSiteQuection(String SiteId, SuperisorID) async {
  var data = await http.post(
      Uri.parse("https://churchiest-dump.000webhostapp.com/question.php"),
      headers: {'Content-Type': 'application/json', 'Charset': 'utf-8'},
      body: jsonEncode({
        "site_id": SiteId,
        "date": DateFormat.yMd().format(DateTime.now()),
        "supervisor_id": SuperisorID
      }));
  if (data.statusCode == 200) {
    print(data.body);
    var jsonResponse = json.decode(data.body);
    return (jsonResponse as List<dynamic>?)
        ?.map((e) => Quections.fromJson(e as Map<String, dynamic>))
        .toList();
  } else {
    print("faild to response Quection list :" + data.body);
  }
}

You also want to know if the inserted value below can be used to snapshot.data [index].inserted after giving it as Future in getSiteQuection Future builder.

class Quections {
  Quections({
    this.the0,
    this.questionId = '',
    this.question = '',
  });

  The0? the0;
  String questionId;
  String question;

  factory Quections.fromRawJson(String str) =>
      Quections.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Quections.fromJson(Map<String, dynamic> json) => Quections(
        the0: The0.fromJson(json["0"]),
        questionId: json["question_id"],
        question: json["question"],
      );

  Map<String, dynamic> toJson() => {
        "0": the0!.toJson(),
        "question_id": questionId,
        "question": question,
      };
}

class The0 {
  The0({
    this.inserted = '',
  });

  String inserted;

  factory The0.fromRawJson(String str) => The0.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory The0.fromJson(Map<String, dynamic> json) => The0(
        inserted: json["inserted"],
      );

  Map<String, dynamic> toJson() => {
        "inserted": inserted,
      };
}

Json

{
    "question_id": "2",
    "question": "Test question"
}{
    "question_id": "3",
    "question": "is it clean?",
    "0": {
        "inserted": "1"
    }
}{
    "question_id": "4",
    "question": "is it good looking?",
    "0": {
        "inserted": "1"
    }
}

This is the Error : https://i.sstatic.net/Du7hs.png


Solution

  • Your json is invalid. Json should have a root. It could be an array element for example

    [
      {
        "question_id": "2",
        "question": "Test question"
      },
      .....
      {
        "0": {
          "inserted": "1"
        },
        "question_id": "4",
        "question": "is it good looking?"
      }
    ]
    

    and plus it should have comma " , " between objects