gpt4 book ai didi

json - 如何在 Flutter 中将响应 JSON 转换为对象?

转载 作者:IT老高 更新时间:2023-10-28 12:44:04 28 4
gpt4 key购买 nike

我正在尝试将成功的 JSON 字符串转换为 Object。可能是我没有以正确的方式做但是我有几个与将 JSON 转换为 Object 相关的问题。

我也在 Log 中得到了这个异常。

NoSuchMethodError: Class '**_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments**.<br>
Receiver: _LinkedHashMap len:3
**Tried calling: cast<Map<String, dynamic>>()**
  1. 我是否也需要在模型中转换该数据对象?
  2. 将 JSON 转换为对象 (SignUpResponse) 的最佳且简单的方法是什么。
  3. 最好用序列化?

响应 JSON:

{
"data": {
"_id": "5bd2a59f4c59de1ac517d7bf",
"email": "fjhsd@gmail.com",
"phoneNumber": "2417874147",
"isAddressApproved": 0,
"unitNumber": "144",
"streetAddress": "sdfsddsf",
"area": "asd",
"zipCode": "112233",
"totalOrder": 0,
"todayOrder": 0,
"isPauseDelivery": false,
"vacationStartDt": null,
"vacationEndDt": null,
"defaultLiter": 1
},
"message": "New User Created",
"error": false
}

由在线工具创建的SignUpResponse。

class SignUpResponse {
Data data;
String message;
bool error;

SignUpResponse({this.data, this.message, this.error});

SignUpResponse.fromJson(Map<String, dynamic> json) {
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
message = json['message'];
error = json['error'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.toJson();
}
data['message'] = this.message;
data['error'] = this.error;
return data;
}
}

class Data {
String sId;
String email;
String phoneNumber;
int isAddressApproved;
String unitNumber;
String streetAddress;
String area;
String zipCode;
int totalOrder;
int todayOrder;
bool isPauseDelivery;
Null vacationStartDt;
Null vacationEndDt;
int defaultLiter;

Data(
{this.sId,
this.email,
this.phoneNumber,
this.isAddressApproved,
this.unitNumber,
this.streetAddress,
this.area,
this.zipCode,
this.totalOrder,
this.todayOrder,
this.isPauseDelivery,
this.vacationStartDt,
this.vacationEndDt,
this.defaultLiter});

Data.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
email = json['email'];
phoneNumber = json['phoneNumber'];
isAddressApproved = json['isAddressApproved'];
unitNumber = json['unitNumber'];
streetAddress = json['streetAddress'];
area = json['area'];
zipCode = json['zipCode'];
totalOrder = json['totalOrder'];
todayOrder = json['todayOrder'];
isPauseDelivery = json['isPauseDelivery'];
vacationStartDt = json['vacationStartDt'];
vacationEndDt = json['vacationEndDt'];
defaultLiter = json['defaultLiter'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['email'] = this.email;
data['phoneNumber'] = this.phoneNumber;
data['isAddressApproved'] = this.isAddressApproved;
data['unitNumber'] = this.unitNumber;
data['streetAddress'] = this.streetAddress;
data['area'] = this.area;
data['zipCode'] = this.zipCode;
data['totalOrder'] = this.totalOrder;
data['todayOrder'] = this.todayOrder;
data['isPauseDelivery'] = this.isPauseDelivery;
data['vacationStartDt'] = this.vacationStartDt;
data['vacationEndDt'] = this.vacationEndDt;
data['defaultLiter'] = this.defaultLiter;
return data;
}
}

调用 REST POST API

void postCallSignUp(BuildContext context, var body) {
// This Function will check Internet is available or not.
Utils.checkConnection().then((connectionResult) {
if (connectionResult) {
http.post(Constants.BASE_URL + Constants.CREATE_USER,
body: body,
headers: {
"Accept": "application/json",
"content-type": "application/json"
}).then((http.Response response) {
final String res = response.body;
final int statusCode = response.statusCode;

if (statusCode < 200 || statusCode > 400 || json == null) {
_onFailureResponse(new Exception("Error while fetching data"));
} else {
//Parsing json response to particular Object.
print(json.decode(res));

// Unable to cast json here...
final parsed = json.decode(res).cast<Map<String, dynamic>>();
parsed.map<SignUpResponse>((json) => SignUpResponse.fromJson(json));
SignUpResponse signUpResponse = parsed.map<SignUpResponse>((json) => SignUpResponse.fromJson(json));
_onSuccessResponse(signUpResponse);
}
});
} else {
_onNoInternetConnection();
Utils.showAlert(context, "Alert", "Internet is not connected.", () {
Navigator.pop(context);
});
}
});
}

无法理解这里发生了什么?为什么我们必须为将 json 转换为特定对象做这么多工作?

最佳答案

不需要使用cast,可以直接解析成Map

final Map parsed = json.decode(res); 

拥有 map 后,您可以使用该数据转换为您的对象。

final signUp = SignUpResponse.fromJson(parsed);

如果你想解析一个对象数组,你可以这样做:

//assuming this json returns an array of signupresponse objects
final List parsedList = json.decode(res);

List<SignUpResponse> list = parsedList.map((val) => SignUpResponse.fromJson(val)).toList();

关于json - 如何在 Flutter 中将响应 JSON 转换为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53001839/

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