我目前正在构建一个应用程序,以通过api读取数据,并且我试图从JSON占位符解析JSON api。
我为用户创建了一个模型类(users_future_model.dart):
class Users {
final int userID;
final String name;
final String username;
final String email;
final Address address;
Users({this.userID, this.name, this.username, this.email, this.address});
factory Users.fromJson(Map<String, dynamic> usersjson)=> Users(
userID: usersjson["id"],
name: usersjson["name"],
username: usersjson["username"],
email: usersjson["email"],
address: Address.fromJson(usersjson["address"])
);
}
class Address{
final String street;
final String suite;
final String city;
final String zipcode;
Address({this.street, this.suite, this.city, this.zipcode});
factory Address.fromJson(Map<String, dynamic> addjson){
return Address(
street: addjson["street"],
suite: addjson["suite"],
city: addjson["city"],
zipcode: addjson["zipcode"]
);
}
}
这是将json读取到小部件中的main.dart:
import 'package:flutter/material.dart';
import 'model/users_future_model.dart';
import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;
final String jsonplaceholder = "http://jsonplaceholder.typicode.com/users/";
//Future method to read the URL
Future<Users> fetchInfo() async{
final response = await http.get(jsonplaceholder);
final jsonresponse = json.decode(response.body);
return Users.fromJson(jsonresponse);
}
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Parse JSON"),
),
body: new Center(
child: new Column(
children: <Widget>[
new FutureBuilder(
future: fetchInfo(),
builder: (context, snapshot){
if(snapshot.hasData){
return new Text(snapshot.data.email);
}else if(snapshot.hasError){
return new Text("Error ${snapshot.error}");
}
})
],
),
)
);
}
}
这是我试图读取的JSON信息,尽管它只是其中的一小部分:
{
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "Sincere@april.biz",
address: {
street: "Kulas Light",
suite: "Apt. 556",
city: "Gwenborough",
zipcode: "92998-3874",
geo: {
lat: "-37.3159",
lng: "81.1496"
}
},
phone: "1-770-736-8031 x56442",
website: "hildegard.org",
company: {
name: "Romaguera-Crona",
catchPhrase: "Multi-layered client-server neural-net",
bs: "harness real-time e-markets"
}
}
我当前遇到的错误是:
Error type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
如何纠正该错误?
答案 0 :(得分:4)
API返回JSON数组而不是json对象,因此列表不是Map。
即用户json是Json Array的第一个元素。
因此要获取第一个元素,请使用第一个索引。 内部获取信息更新
return Users.fromJson(jsonresponse[0]);
答案 1 :(得分:3)
var streetsFromJson = parsedJson['streets'];
List<String> streetsList = new List<String>.from(streetsFromJson);
Thnx for https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51
答案 2 :(得分:0)
答案 3 :(得分:0)
只需注意错误
List<dynamic> is not a subtype of type Map<String, dynamic>
基本上,这意味着您单击Web服务后所接收的数据为List形式,但内部使用的数据类为Map类型。因此,由于Map不匹配,由于结构不匹配,它无法解析数据在数据类中定义,而不是在列表中定义。
重新检查您的Json响应和相应的PODO类
答案 4 :(得分:0)
查看此答案
Future<List<ProductList>> getProductList() async {
print("comes");
String productURl= mainURL+'api/store/product-with-category/';
final response = await http.get(productURl,headers:{"Content-Type":
"application/json"});
List jsonResponse = json.decode(response.body);
return jsonResponse.map((job) => new ProductList.fromJson(job)).toList();
}
获取功能
FutureBuilder<List<ProductList>>(
future: getProductList(),
builder: (context, snapshot) {
print("snapshot");
print(snapshot.data);
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
itemCount: snapshot.data.length,
gridDelegate:SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2,),
itemBuilder: (BuildContext context, int i){
return Card(
child: Container(
decoration: BoxDecoration(
border: Border.all(width: 0.5,color: Colors.grey)
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
text18(snapshot.data[i].title, Colors.black, FontWeight.bold)
],
),
),
),
);
}
)
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
只需更改URL并创建模型类
答案 5 :(得分:0)
使用
List<dynamic> output = jsonDecode(yourJsonSource);
代替
Map<String, dynamic> output = jsonDecode(yourJsonSource);
答案 6 :(得分:0)
另一种轻松做到这一点的方法:
import 'package:json_helpers/json_helpers.dart';
void main() {
// If request returns list of users
var body = '[{"id": 1}, {"id": 2} ]';
final users = body.jsonList((e) => User.fromJson(e));
assert(users[1].id == 2);
print(users[1].id);
// If request returns the user
body = '{"id": 1}';
final user = body.json((e) => User.fromJson(e));
assert(user.id == 1);
print(user.id);
}