下面的代码对node.js服务器进行rest调用,该服务器返回一个包含一系列值的json,这些值必须通过将值强制转换为 Cantiere 类型对象插入列表中。我该怎么做呢?
我想要做的是将每个json转换为构造类型的对象,然后将它们插入列表中。
JSON call 波动:
static Future<List> Ricerca(Utente u, int IdCantiere, String NomeCantiere,
String RagioneSociale, bool isUtente) async {
var ret;
Map map = {
'IdUtente': u.GetIdUtente(),
'IdCantiere': IdCantiere,
'NomeCantiere': "a",
'RagioneSociale': RagioneSociale,
'CheckBoxCantieriCreatiDaUtenteLoggato': isUtente
};
String value = await apiRequest("/cantieri/ricerca", map);
//The ret variable holds the json, what I want to do is create a list of Cantiere type objects.
ret = json.decode(value);
return (ret as Iterable<dynamic> ?? const <dynamic>[])
.map((dynamic jsonObject) => Cantiere(
new Cliente(
jsonObject["IdCliente"] as int,
jsonObject["RagioneSociale"] as String,
jsonObject["Filiale"] as String,),
jsonObject["IdCantiere"] as int,
jsonObject["NomeCantiere"] as String,
jsonObject["DescrizioneEstesa"] as String,
jsonObject["Tipologia"] as String,
jsonObject["Stato"] as String,
jsonObject["StatoFatturazione"] as String,
jsonObject["DataCreazione"] as String,
))
.toList();
}
Cantiere.dart和Cliente.dart
class Cliente {
int _IdCliente;
String _RagioneSociale;
String _Filiale;
Cliente(this._IdCliente, this._RagioneSociale, this._Filiale);
String GetRagioneSociale() {
return this._RagioneSociale;
}
}
//Classe che rappresenta il cantiere
class Cantiere {
String _NomeCantiere,
_Tipologia,
_Stato,
_StatoFatturazione,
_DescrizioneEstesa,
_DataCreazione;
int _IdCantiere;
Cliente _c;
Cantiere(
this._c,
this._IdCantiere,
this._NomeCantiere,
this._DescrizioneEstesa,
this._Tipologia,
this._Stato,
this._StatoFatturazione,
this._DataCreazione);
}
JSON示例:
[
{
"IdCantiere": 4,
"IdCliente": 40,
"Filiale": "SEDE",
"RagioneSociale": "Ca asas",
"NomeCantiere": "sala dd",
"DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
"Tipologia": "Consuntivo",
"StatoCantiere": "Chiuso",
"StatoFatturazione": 1,
"DescrizioneEstesa": "asasas"
},
"IdCantiere": 5,
"IdCliente": 40,
"Filiale": "SEDE",
"RagioneSociale": "Ca asas",
"NomeCantiere": "sala dd",
"DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
"Tipologia": "Consuntivo",
"StatoCantiere": "Chiuso",
"StatoFatturazione": 1,
"DescrizioneEstesa": "asasas"
}
]
最佳答案
jsonDecode
所做的实际上是将JSON字符串转换为包含原始类型的List
和Map
序列,具体取决于它是JSON数组还是JSON对象还是JSON原语。
因此,输出的类型(基于提供的JSON代码段)为List
,其中包含许多Map
s(但这并不是说该类型实际上是List<Map>
)。
要获得所需结果,必须将每个JSON对象从解码的JSON映射到所需的对象类型:
return (ret as Iterable<dynamic> ?? const <dynamic>[])
.map((dynamic jsonObject) =>
Cliente(
jsonObject["IdCliente"] as int,
jsonObject["RagioneSociale"] as String,
jsonObject["Filiale"] as String,
)
)
.toList();
关于json - 将列表转换到dart中的对象列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60276410/