gpt4 book ai didi

flutter - Dart - 解析嵌套的 Json 数组

转载 作者:IT王子 更新时间:2023-10-29 07:18:39 24 4
gpt4 key购买 nike

尝试使用 dart 的工厂概念转换嵌套的 JSON 数据后出现错误。这里我有两个类来处理 json 数据,但仍然出现此错误:

Exception has occurred. _TypeError (type 'FormatException' is not a subtype of type '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);
}

如果这有帮助,请告诉我。

关于flutter - Dart - 解析嵌套的 Json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56506225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com