我想将此json转换为object。我的问题出在子键“ rates”上。请帮帮我。
{
"info": "Exchange Rates",
"timestamp": "1558080000",
"rates": {
"USD": "1,536.7",
"VND": "6.5693",
"PHP": "29.184",
"KRW": "128.60",
"HKD": "195.77",
"BRL": "379.62",
"RSD": "14.557",
"MYR": "367.94"
}
}
答案 0 :(得分:0)
您可以使用此网站生成与您的json映射匹配的类。 json_to_dart
这一代将产生具有属性信息,时间戳和费率的高级类,以及具有属性(USD,VND等)的嵌入式类Rate。请参见下面的代码:
class ExchangeRate {
String info;
String timestamp;
Rates rates;
ExchangeRate({this.info, this.timestamp, this.rates});
ExchangeRate.fromJson(Map<String, dynamic> json) {
info = json['info'];
timestamp = json['timestamp'];
rates = json['rates'] != null ? new Rates.fromJson(json['rates']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['info'] = this.info;
data['timestamp'] = this.timestamp;
if (this.rates != null) {
data['rates'] = this.rates.toJson();
}
return data;
}
}
class Rates {
String uSD;
String vND;
String pHP;
String kRW;
String hKD;
String bRL;
String rSD;
String mYR;
Rates(
{this.uSD,
this.vND,
this.pHP,
this.kRW,
this.hKD,
this.bRL,
this.rSD,
this.mYR});
Rates.fromJson(Map<String, dynamic> json) {
uSD = json['USD'];
vND = json['VND'];
pHP = json['PHP'];
kRW = json['KRW'];
hKD = json['HKD'];
bRL = json['BRL'];
rSD = json['RSD'];
mYR = json['MYR'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['USD'] = this.uSD;
data['VND'] = this.vND;
data['PHP'] = this.pHP;
data['KRW'] = this.kRW;
data['HKD'] = this.hKD;
data['BRL'] = this.bRL;
data['RSD'] = this.rSD;
data['MYR'] = this.mYR;
return data;
}
}
然后,您可以使用fromJson()的构造函数构造对象。
Map<String, dynamic> json = {"info":"Exchange Rates","timestamp":"1558080000","rates":{"USD":"1,536.7","VND":"6.5693","PHP":"29.184","KRW":"128.60","HKD":"195.77","BRL":"379.62","RSD":"14.557","MYR":"367.94"}};
var exRate = new ExchangeRate.fromJson(json);