[英]How to parse a graphql response in flutter
I am trying to parse my graphql response from my neo4j-graphql backend in my flutter app. 我正在尝试从flutter应用程序中的neo4j-graphql后端解析我的graphql响应。 I am using the flutter_graphql plugin to make queries to the back end. 我正在使用flutter_graphql插件对后端进行查询。 However, when I try to parse the response(JSON) I am getting 'LinkHashMap is not a subtype of Users Map.' 但是,当我尝试解析响应(JSON)时,出现“ LinkHashMap不是用户映射的子类型”。
I tried modifying my serializing classes that will parse the response but to no available .below is the JSON response from neo4j graphql 我尝试修改我的序列化类以解析响应但没有可用的。以下是neo4j graphql的JSON响应
/*I HAVE EDITED THE JSON RESPONSE. THE FULL JSON RESPONSE FROM THE SERVER IS AS BELOW*/
{
"data": {
"User": [
{
"userId": 1,
"city": "NewYork",
"country": "User",
"captionType": "User",
"state": "New York",
"firstName": "example2",
"lastname": "example",
"email": "example2@gmail.com"
}
]
},
"extensions": {
"type": "READ_ONLY"
}
}
below are the classes that represent the above response 以下是代表以上响应的类
@JsonSerializable()
class User {
final int userId;
final String email ;
final String country ;
final String firstName;
final String gender ;
final String city ;
final String dateOfBirth ;
final String state;
final String captionType;
final String lastname;
User({this.userId,this.email,this.country,this.firstName,this.gender,this.dateOfBirth,this.state,this.captionType,this.city,this.lastname});
factory User.fromJson(Map<String,dynamic> json)=> _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
class Users{
final List<User>users;
Users({this.users});
factory Users.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['users'] as List;
List<User> usersList = list.map((i) => User.fromJson(i)).toList();
return Users(
users: usersList
);
}
}
//below is the graphql configuration in my seperate GraphQl.dart file
class GraphQLConfiguration {
static HttpLink httpLink = HttpLink(
uri: "http://localhost:7474/graphql/",
headers: {
HttpHeaders.authorizationHeader: ************",
},
);
static final AuthLink authLink = AuthLink(
getToken: () async => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
// OR
// getToken: () => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
);
static ValueNotifier<GraphQLClient> initailizeClient() {
ValueNotifier<GraphQLClient> client = ValueNotifier(
GraphQLClient(
cache: InMemoryCache(),
link: httpLink,
),
);
return client;
}
static GraphQLClient clientToQuery() {
return GraphQLClient(
cache: OptimisticCache(
dataIdFromObject: typenameDataIdFromObject),
link: httpLink,
);
}
}
//below is my main.dart file where am trying to parse the response
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: true,
title: 'Flutter Graphql Client',
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (context) => MyHomePage(), //RootPage(auth: new Auth(),),
},
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget listViewWidget(List<Users> users) {
return MediaQuery.removePadding(
context: context, removeTop: true,
child: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return Container(
child: Column(
children: <Widget>[
Text('users:$users'),
],
),
);
}),
);
}
String readUser = """
query{
User(userId:1){
userId
city
country
captionType
state
firstName
lastname
email
}
}
""";
@override
Widget build(BuildContext context) {
return GraphQLProvider(
client: GraphQLConfiguration.initailizeClient(),
child: CacheProvider(
child: Scaffold(
appBar: AppBar(
title: Text('Flutter Graphql Client'),
),
body:Query(
options: QueryOptions(
document: readUser),
builder: (QueryResult result, {VoidCallback refetch, FetchMore fetchMore}) {
if (result.errors!= null) {
print('$result.errors');
return Text(result.errors.toString());
} if (result.errors== null){
print(('$result'));
print(('${result.data}'));
} if (result.loading){
return Center(
child: CupertinoActivityIndicator(
radius: 13.0,
));
}
return listViewWidget(result.data);
},
)
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
),
),
));
}
}
I am expecting the info to be parsed through the Users class and displayed through the listViewWidget. 我希望该信息将通过Users类进行解析,并通过listViewWidget显示。 However I am getting'LinkHashMap is not a subtype of Users Map.' 但是我得到'LinkHashMap不是用户映射的子类型。
You can parse any JSON using https://app.quicktype.io/ , below is the model class for your JSON 您可以使用https://app.quicktype.io/解析任何JSON,以下是JSON的模型类
// To parse this JSON data, do
//
// final responseModel = responseModelFromJson(jsonString);
import 'dart:convert';
ResponseModel responseModelFromJson(String str) => ResponseModel.fromJson(json.decode(str));
String responseModelToJson(ResponseModel data) => json.encode(data.toJson());
class ResponseModel {
Data data;
Extensions extensions;
ResponseModel({
this.data,
this.extensions,
});
factory ResponseModel.fromJson(Map<String, dynamic> json) => ResponseModel(
data: json["data"] == null ? null : Data.fromJson(json["data"]),
extensions: json["extensions"] == null ? null : Extensions.fromJson(json["extensions"]),
);
Map<String, dynamic> toJson() => {
"data": data == null ? null : data.toJson(),
"extensions": extensions == null ? null : extensions.toJson(),
};
}
class Data {
List<User> user;
Data({
this.user,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
user: json["User"] == null ? null : List<User>.from(json["User"].map((x) => User.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"User": user == null ? null : List<dynamic>.from(user.map((x) => x.toJson())),
};
}
class User {
int userId;
String city;
String country;
String captionType;
String state;
String firstName;
String lastname;
String email;
User({
this.userId,
this.city,
this.country,
this.captionType,
this.state,
this.firstName,
this.lastname,
this.email,
});
factory User.fromJson(Map<String, dynamic> json) => User(
userId: json["userId"] == null ? null : json["userId"],
city: json["city"] == null ? null : json["city"],
country: json["country"] == null ? null : json["country"],
captionType: json["captionType"] == null ? null : json["captionType"],
state: json["state"] == null ? null : json["state"],
firstName: json["firstName"] == null ? null : json["firstName"],
lastname: json["lastname"] == null ? null : json["lastname"],
email: json["email"] == null ? null : json["email"],
);
Map<String, dynamic> toJson() => {
"userId": userId == null ? null : userId,
"city": city == null ? null : city,
"country": country == null ? null : country,
"captionType": captionType == null ? null : captionType,
"state": state == null ? null : state,
"firstName": firstName == null ? null : firstName,
"lastname": lastname == null ? null : lastname,
"email": email == null ? null : email,
};
}
class Extensions {
String type;
Extensions({
this.type,
});
factory Extensions.fromJson(Map<String, dynamic> json) => Extensions(
type: json["type"] == null ? null : json["type"],
);
Map<String, dynamic> toJson() => {
"type": type == null ? null : type,
};
}
use this code to parse your response 使用此代码来解析您的响应
ResponseModel responseModel = responseModelFromJson(result.data);
return listViewWidget(responseModel.data.user);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.