这是我的API响应,我希望所有建筑物名称都包含在字符串列表中
{
"entity_id": "86",
"building_name": "Burj Khalifa",
"location": "Al Ttay",
"image_field": "1595916594oad.jpeg"
},
{
"entity_id": "87",
"building_name": "Azmair",
"location": " Eyal Nasser ",
"image_field": "1596541099s.jpeg"
},
]
我尝试了这个但没用
List<String> _buildlist = (jsonDecode(response['building_name']) as List<dynamic>).cast<String>();
print(_buildlist);
答案 0 :(得分:3)
您需要解码JSON,然后将每个元素map
转换为相关的字符串,然后将它们重新组成一个列表:
var decoded = json.decode(j) as List;
var names = decoded.map<String>((e) => e['building_name']).toList();
print(names); // prints [Burj Khalifa, Azmair]
答案 1 :(得分:0)
使用“ dart:convert”包尝试以下操作:
class examClass:
def __init__(self, logger_tag):
self.name = 'logger'
self.logger = logging.getLogger(logger_tag + "." + self.name)
self.logger.info("Created an instance of " + self.name)
def __del__(self):
class_name = self.__class__.__name__
self.logger.info("%s destroyed" % class_name)
您可以在https://dartpad.dev/中运行代码并对其进行测试
答案 2 :(得分:0)
首先,您需要在数组列表中获取所有字段的值。为此,您首先需要解析所有响应。为使用app.quicktype.io的任何响应创建适当的模型类。这是来自app.quicktype.io的模型类,
import 'dart:convert';
List<ParseResponse> parseResponseFromJson(String str) => List<ParseResponse>.from(json.decode(str).map((x) => ParseResponse.fromJson(x)));
String parseResponseToJson(List<ParseResponse> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class ParseResponse {
ParseResponse({
this.entityId,
this.buildingName,
this.location,
this.imageField,
});
String entityId;
String buildingName;
String location;
String imageField;
factory ParseResponse.fromJson(Map<String, dynamic> json) => ParseResponse(
entityId: json["entity_id"],
buildingName: json["building_name"],
location: json["location"],
imageField: json["image_field"],
);
Map<String, dynamic> toJson() => {
"entity_id": entityId,
"building_name": buildingName,
"location": location,
"image_field": imageField,
};
}
现在,如果您调用parseResponseFromJson(resonseString);那么您将获得列表,然后可以从这里开始。
答案 3 :(得分:0)
您首先需要使用json.decode()将JSON转换为Maps
以下代码显示了我的方法:
import 'dart:convert';
void main() {
var response =[
{
"entity_id": "86",
"building_name": "Burj Khalifa",
"location": "Al Ttay",
"image_field": "1595916594oad.jpeg"
},
{
"entity_id": "87",
"building_name": "Azmair",
"location": " Eyal Nasser ",
"image_field": "1596541099s.jpeg"
},
];
List<String> _buildlist = List();
List<Map<String,String>> data = json.decode(response);
for(Map<String,String> i in data)
_buildlist.add(i["building_name"]);
print(_buildlist);
}