繁体   English   中英

如何将 json 解析为 object 并在另一个 class 中使用

[英]How do parse json to object and use in another class

如何将 JSON 解析为 object 并在另一个 class 中使用? 例如,我收到响应并创建 class。

signIn(String userName, pass) async {

 final String serverKey = '##############';
 final String url = 'https://example.com';

 Map data = {
 'server_key': serverKey,
 'username': userName,
 'password': pass };
 var jsonResponse;
 var response = await http.post(url, body: data);
 if (response.statusCode == 200) {
 jsonResponse = json.decode(response.body);
 var res = jsonResponse;
 print(res);
 list = res.map<Token>((json) => Token.fromJson(json)).toList();
 if (jsonResponse != null) {
 setState(() {
  _isLoading = false;
 });
}
} else {
 setState(() {
 _isLoading = false;
 });
  print(response.body);
 }

创建 class

class Token {
  String timezone;
  String access;

Token({this.timezone, this.access});
factory Token.fromJson(Map<String, dynamic> json) {
 return Token(timezone: json["timezone"], access: json["access_token"]);
  }
}

以及如何将另一个 dart 文件中的 var access 和 timezone 使用到项目中?

嗨 kakajan 我在 dart 文件中使用数据的方式是。 步骤1:创建一个Global.dart(不要在里面声明一个class),在这里声明变量就是

var access;
var timezone;

Step 2: Import this Global.dart into the file you have the sign in function Step 3: assign this variables the data you get from the API from server Step 4: After the data is assign please confirm it using print statements Step 5: Go到您想要数据的另一个 dart 文件并导入 Global.dart 第 6 步:您可以在那里轻松使用这些变量

请注意,这只会持续到应用程序关闭后的一个应用程序实例,除非您首先调用 function 中的标志,否则它们将没有任何价值:)希望我能提供帮助:)

使用 build_runner package 生成您的 json 解析方法并用于将 json 转换为 ZA8CFDE63311C46EB2ACZ6B86 反之亦然。

这是一个例子:

import 'package:json_annotation/json_annotation.dart';

part 'user_model.g.dart';

@JsonSerializable()
class User {
  final String userName;
  final String authKey;
  final String role;

  User({this.userName, this.authKey, this.role});

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

user_model.g.dart文件将在您运行flutter pub run build_runner build时创建。 有关更多用法,请查看 package 页面https://pub.dev/packages/build_runner#built-in-commands

将 Json 转换为用户 object

Future<User> _getToken() async {
    final data = await FlutterSession().get("user"); //this could be also from API call
    if (data != null) {
      User user = User.fromJson(data);
      if (user.userName == null)
        return new User(authKey: null);
      else
        return User.fromJson(data);
    } else {
      return new User(authKey: null);
    }
  }

鉴于您的pubspec.yaml中有所有这些包的条件

json_to_model: ^1.4.0
build_runner: ^1.12.2
json_serializable: ^3.2.5

注意:版本可能不同,您需要从https://pub.dev/packages 获取

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM