Отображение экземпляра class_name вместо данных - PullRequest
0 голосов
/ 07 августа 2020

Я пытаюсь получить данные из API, но при выполнении следующего кода я получаю ответ только как «Экземпляр класса Survey», но не как фактические данные в API. Вот код, который я использую:

Future GetSurvey() async {
    var response = await http.get(
      url,
      headers: {
        "Accept": "application/json"
      }
    );
if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.
      var data = convertoJson['Item'];
      print(Questions.fromjson(data));*/

      Map<String, dynamic> map = json.decode(response.body);
      var data = map['Item'];
      Survey survey = new Survey.fromjson(data);
      print(survey.questions);


    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load album');
    }



  }

}

class Questions{
  String questions;

  Questions({this.questions});

  factory Questions.fromjson(Map<String, dynamic> json){


    //var questionfromjson = json['question'];
    //List<String> questionslist = new List<String>.from(questionfromjson);

    return Questions(
      questions: json['question']
    );
  }

}

class Survey{
  String surveyid;
  List<Questions> questions;

  Survey({this.surveyid,this.questions});

  factory Survey.fromjson(Map<String, dynamic> json){

    var list = json['QUESTIONS'] as List;
    print(list.runtimeType);

    List<Questions> questionslist = list.map((e) => Questions.fromjson(e)).toList();

    return Survey(
      surveyid: json['OS_ID'],
      questions: questionslist
    );
  }

}

Ниже приведен формат API:

{
    "Item":
    {
        "OS_ID": "759",
        "QUESTIONS":[
        {
            "rule":,
            "question": "How much is the value"
        },
        {
            "rule":,
            "question": "Describe the view"
        }
    }
}

1 Ответ

0 голосов
/ 07 августа 2020

Не о чем беспокоиться, ваш код в порядке. Просто нужно переопределить функцию toString() внутри вашего класса модели ..

@override
  String toString() {
    return 'questions{questions: $questions}';
  }
...