dart flutter中控制台打印错误的json格式

pxy2qtax  于 2023-03-10  发布在  Flutter
关注(0)|答案(1)|浏览(214)

我试图解析flutter中的json数据,但似乎json数据的格式不正确,当我在浏览器中检查时,json数据的格式正确。下面我附上了两个截图。我使用express创建了自己的本地服务器,我认为它不需要在这里,因为我在浏览器中得到了良好的响应。如果需要,我可以在这里共享或更新。x1c 0d1x

有人能解释一下这里出了什么问题吗?我无法用Flutter控制台中得到的响应解析数据。
我正在使用下面的代码转换

import 'dart:convert';

Tasks tasksFromJson(String str) => Tasks.fromJson(json.decode(str));

String tasksToJson(Tasks data) => json.encode(data.toJson());

class Tasks {
  Tasks({
    required this.tasks,
  });

  List<Task> tasks;

  factory Tasks.fromJson(Map<String, dynamic> json) => Tasks(
    tasks: List<Task>.from(json["tasks"].map((x) => Task.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "tasks": List<dynamic>.from(tasks.map((x) => x.toJson())),
  };
}

class Task {
  Task({
    required this.completed,
    required this.id,
    required this.name,
    required this.v,
  });

  bool completed;
  String id;
  String name;
  int v;

  factory Task.fromJson(Map<String, dynamic> json) => Task(
    completed: json["completed"],
    id: json["_id"],
    name: json["name"],
    v: json["__v"],
  );

  Map<String, dynamic> toJson() => {
    "completed": completed,
    "_id": id,
    "name": name,
    "__v": v,
  };
}

那么

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:task_manager/constants/constants.dart';
import 'package:task_manager/models/tasks_model.dart';

class DioClient {
  final Dio dio = Dio();

  Future fetchTasks() async {
    try{
      final response = await dio.get(baseURL+"/tasks");
      final tasks = tasksFromJson(response.data);
      debugPrint("${response.data}");
    } on DioError catch(e){
      debugPrint("StatusCode: ${e.toString()}");
      throw Exception("Failed to load Tasks");
    }
  }
}

错误是

Error: Expected a value of type 'String', but got one of type '_JsonMap'
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49      throw_
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 99:3        castError
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 485:10  cast
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 719:17                as
packages/task_manager/services/dio_client.dart 12:21                                                                           fetchTasks
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50                <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1660:54                                              runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18                                        handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 767:44                                        handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 796:13                                        _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 558:7                                         [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 47:12                                         complete
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future.dart 613:44                                             onValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1660:54                                              runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18                                        handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 767:44                                        handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 796:13                                        _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 567:5                                         [_completeWithValue]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 640:7                                         callback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 40:11                                  _microtaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 49:5                                   _startMicrotaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15               <fn>

更新!!毕竟,我知道Dio将来自REST API的JSON响应编码为响应

我们可以停止此操作以在Dio选项中获取纯数据

options: Options( 
    responseType: ResponseType.plain,
  )

或低于可接受的答案也将起作用。

ffscu2ro

ffscu2ro1#

似乎response.data已经是一个JsonMap。
尝试改变这一点:

final tasks = tasksFromJson(response.data);

用这个

import 'dart:convert';
// ...
final tasks = tasksFromJson(jsonEncode(response.data));

更新:
一个更好的解决方案是这样的:

Tasks.fromJson(Map.from(response.data));

相关问题