void getHttp() async {
var url = 'https://**********************/AppAccess/GetRestaurantCategoryList';
try {
var response = await Dio().get(url);
if (response.statusCode == HttpStatus.ok) {
var json = jsonDecode(response.data);
for (var item in json["data"]) {
var model = FoodItem.fromJson(item);
print(model.categoryId);
print(model.categoryName);
}
} catch (e) {
print(e);
}
注意上面是直接Json转换成实体,下面是根据json中的键值对,取值。
带有async的方法返回值必须是Future
Future getHomePageContent() async {
try {
Response response;
Dio dio = new Dio();
response = await dio.get("https://**********************/AppAccess/GetRestaurantCategoryList");
if (response.statusCode == HttpStatus.ok) {
var resdata= jsonDecode(response.data);
for (var item in resdata["data"]) {
FoodItem model =new FoodItem();
model.categoryId=item["CategoryId"];
model.categoryName=item["CategoryName"];
print(model.categoryId);
print(model.categoryName);
}
return response.data;
} else {
throw Exception("...-");
}
} catch (e) {
return print("error:" + e.toString());
}
}
实体 (https://javiercbk.github.io/json_to_dart/ 可以自动的把json生产model)
class FoodItem {
int? categoryId;
String? categoryName;
String? createdBy;
String? createdDateTime;
String? updatedBy;
String? updatedDateTime;
String? isDel;
FoodItem(
{this.categoryId,
this.categoryName,
this.createdBy,
this.createdDateTime,
this.updatedBy,
this.updatedDateTime,
this.isDel});
FoodItem.fromJson(Map<String, dynamic> json) {
categoryId = json['CategoryId'];
categoryName = json['CategoryName'];
createdBy = json['CreatedBy'];
createdDateTime = json['CreatedDateTime'];
updatedBy = json['UpdatedBy'];
updatedDateTime = json['UpdatedDateTime'];
isDel = json['IsDel'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['CategoryId'] = this.categoryId;
data['CategoryName'] = this.categoryName;
data['CreatedBy'] = this.createdBy;
data['CreatedDateTime'] = this.createdDateTime;
data['UpdatedBy'] = this.updatedBy;
data['UpdatedDateTime'] = this.updatedDateTime;
data['IsDel'] = this.isDel;
return data;
}
}
json
{
"data": [
{
"CategoryId": 17,
"CategoryName": "Coffee",
"CreatedBy": null,
"CreatedDateTime": null,
"UpdatedBy": null,
"UpdatedDateTime": null,
"IsDel": null
},
{
"CategoryId": 18,
"CategoryName": "Fruit",
"CreatedBy": null,
"CreatedDateTime": null,
"UpdatedBy": null,
"UpdatedDateTime": null,
"IsDel": null
}
]
}