https://picsum.photos/v2/list?page=1&limit=50 我正在使用此Json文件,但是当我尝试对其进行解码时,它显示为null。
我尝试过
'''
List imgData;
final String url = 'https://picsum.photos/v2/list?page=1&limit=50';
Future getData() async {
var response = await http
.get(Uri.encodeFull(url), headers: {'Accept': 'application/json'});
List data = jsonDecode(response.body)['results'];
setState(() {
imgData = data;
});
}
@override
void initState() {
super.initState();
this.getData();
}
'''
答案 0 :(得分:0)
尝试在下面替换
List data = jsonDecode(response.body)['results'];
与
List data = jsonDecode(response.body);
JSON中没有结果参数
答案 1 :(得分:0)
您可以使用JSON to dart tool,它是免费在线提供的。
将JSON粘贴到左侧面板,然后从右上角选择dart语言,
您将获得dart类代码,在其中可以使用.toMap()和.toJson()之类的方法,
速度非常快,人为错误也较少。
这对于处理巨大的JSON数据非常有帮助。
您将通过此工具为数据获取此类。
// To parse this JSON data, do
//
// final data = dataFromJson(jsonString);
import 'dart:convert';
List<Data> dataFromJson(String str) => List<Data>.from(json.decode(str).map((x) => Data.fromMap(x)));
String dataToJson(List<Data> data) => json.encode(List<dynamic>.from(data.map((x) => x.toMap())));
class Data {
String id;
String author;
int width;
int height;
String url;
String downloadUrl;
Data({
this.id,
this.author,
this.width,
this.height,
this.url,
this.downloadUrl,
});
factory Data.fromMap(Map<String, dynamic> json) => Data(
id: json["id"],
author: json["author"],
width: json["width"],
height: json["height"],
url: json["url"],
downloadUrl: json["download_url"],
);
Map<String, dynamic> toMap() => {
"id": id,
"author": author,
"width": width,
"height": height,
"url": url,
"download_url": downloadUrl,
};
}
此后,您可以使用dataFromJson方法。
这可以完全实现您的代码。
import 'dart:convert';
List imgData;
final String url = 'https://picsum.photos/v2/list?page=1&limit=50';
Future getData() async {
var response = await http
.get(Uri.encodeFull(url), headers: {'Accept': 'application/json'});
List data = dataFromJson(response.body);
setState(() {
imgData = data;
});
}
@override
void initState() {
super.initState();
this.getData();
}
List<Data> dataFromJson(String str) => List<Data>.from(json.decode(str).map((x) => Data.fromMap(x)));
String dataToJson(List<Data> data) => json.encode(List<dynamic>.from(data.map((x) => x.toMap())));
class Data {
String id;
String author;
int width;
int height;
String url;
String downloadUrl;
Data({
this.id,
this.author,
this.width,
this.height,
this.url,
this.downloadUrl,
});
factory Data.fromMap(Map<String, dynamic> json) => Data(
id: json["id"],
author: json["author"],
width: json["width"],
height: json["height"],
url: json["url"],
downloadUrl: json["download_url"],
);
Map<String, dynamic> toMap() => {
"id": id,
"author": author,
"width": width,
"height": height,
"url": url,
"download_url": downloadUrl,
};
}