尝试使用DART的工厂概念转换嵌套的JSON数据后出错。
在这里,我有两个类来处理JSON数据,但仍然得到这个错误:
发生异常。
_类型错误(类型“formatException”不是类型“map”的子类型)
代码如下:


    class BodyResponse {
      final Map<String, dynamic> message;
      BodyResponse({
        this.message
      });
      factory BodyResponse.fromJson(Map<String, dynamic> json) {
        return BodyResponse(message: json['message']);
      }
    }

    class ErrorResponse {
      final BodyResponse body;
      final int status;
      final String contentType;
      final bool success;

      ErrorResponse({
        this.body, this.status, this.contentType, this.success
      });

      factory ErrorResponse.fromJson(Map<String, dynamic> json) {
        return ErrorResponse(
          body: BodyResponse.fromJson(json['body']),
          status: json['status'],
          contentType: json['content_type'],
          success: json['success']
        );
      }
    }

    ErrorResponse errors = ErrorResponse.fromJson("""
      {
        "body": {
          "message": "Some one has already taken this username(fooBar), please try again with a new username."
        },
        "status": 500,
        "content_type": "application\/json",
        "success": false
      }
    """);

    print(errors);

这里可能出什么问题?

最佳答案

在这里修改了大部分代码。希望这就是你努力实现的目标。

import 'dart:convert';

class BodyResponse {
  final String message;
  BodyResponse({this.message});

  BodyResponse.fromJson(Map<String, dynamic> json):
    message = json['message'];

  factory BodyResponse.fromString(String encodedJson) {
    return BodyResponse.fromJson(json.decode(encodedJson));
  }

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

  String toString() => json.encode(this.toJson());

}

class ErrorResponse {
  final BodyResponse body;
  final int status;
  final String contentType;
  final bool success;

  ErrorResponse({this.body, this.status, this.contentType, this.success});

  ErrorResponse.fromJson(Map<String, dynamic> json):
    body = BodyResponse.fromJson(json['body']),
    status = json['status'],
    contentType = json['content_type'],
    success = json['success'];

  factory ErrorResponse.fromString(String encodedJson) {
    return ErrorResponse.fromJson(json.decode(encodedJson));
  }

  Map<String, dynamic> toJson() => {
    "body": body.toJson(),
    "status": status,
    "contentType": contentType,
    "success": success,
  };

  String toString() => json.encode(this.toJson());

}

void main() {
  ErrorResponse errors = ErrorResponse.fromString("""
      {
        "body": {
          "message": "Some one has already taken this username(fooBar), please try again with a new username."
        },
        "status": 500,
        "content_type": "application\/json",
        "success": false
      }
    """);
  print(errors);
}

如果有帮助,请告诉我。

09-08 12:02