gpt4 book ai didi

json - 如何在 flutter 中解析graphql响应

转载 作者:行者123 更新时间:2023-12-03 03:01:32 25 4
gpt4 key购买 nike

我正在尝试从我的 flutter 应用程序中的 neo4j-graphql 后端解析我的 graphql 响应。我正在使用 flutter_graphql 插件向后端进行查询。但是,当我尝试解析响应(JSON)时,我得到“LinkHashMap 不是用户映射的子类型”。

我尝试修改将解析响应但没有可用的序列化类。下面是来自 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"
}
}

以下是代表上述响应的类

    @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),
),
),
));
}
}


我希望通过 Users 类解析信息并通过 listViewWidget 显示。但是我得到“LinkHashMap 不是用户映射的子类型”。

最佳答案

您可以使用 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,
};
}

使用此代码解析您的响应
ResponseModel  responseModel = responseModelFromJson(result.data);
return listViewWidget(responseModel.data.user);

关于json - 如何在 flutter 中解析graphql响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57889198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com