【问题标题】:Displaying 'Instance of class_name' instead of data显示“类名实例”而不是数据
【发布时间】:2020-08-07 05:23:15
【问题描述】:

我正在尝试从 API 获取数据,但在执行以下代码时,我得到的响应仅为“调查类实例”,而不是 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"
        }
    }
}

【问题讨论】:

  • 请发帖minimal reproducible example。您的代码无法编译,即使可以编译,它也会打印出与您发布的消息不同的消息。

标签: flutter dart flutter-http


【解决方案1】:

不用担心,您的代码没问题。只需要覆盖模型类中的toString() 函数..

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

【讨论】:

  • 谢谢。我可以得到一个问题,但它仍然是 json 格式,如何将其转换为字符串格式?
  • 它显示为:问题{问题:价值是多少}
  • 您可以随意修改。就像如果你返回 $questions 一样,你只能得到问题
  • 好的。谢谢。
  • 如果您找到了答案而不是认为这是正确的并投反对票:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 2018-07-21
  • 1970-01-01
相关资源
最近更新 更多