简体   繁体   English

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

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

How do parse JSON to object and use in another class?如何将 JSON 解析为 object 并在另一个 class 中使用? For example, I get a response and create 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);
 }

Create class创建 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"]);
  }
}

And how to use var access and timezone in another dart file into the project?以及如何将另一个 dart 文件中的 var access 和 timezone 使用到项目中?

hi kakajan the way I use data across dart file is.嗨 kakajan 我在 dart 文件中使用数据的方式是。 Step 1: Create a Global.dart (Dont declare a class within it), declare the variables here that is步骤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 to the other dart file where you want the data and import Global.dart Step 6: You can easily use those variables there 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 步:您可以在那里轻松使用这些变量

Note this only would persist till the one instance of app once app is closed they wont be having any value unless you call the sign in function first: ) Hope I could help: )请注意,这只会持续到应用程序关闭后的一个应用程序实例,除非您首先调用 function 中的标志,否则它们将没有任何价值:)希望我能提供帮助:)

Use build_runner package to generate your json parse methods and use to convert json to object and vice versa.使用 build_runner package 生成您的 json 解析方法并用于将 json 转换为 ZA8CFDE63311C46EB2ACZ6B86 反之亦然。

Here is an example:这是一个例子:

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 file will be created when you run flutter pub run build_runner build . user_model.g.dart文件将在您运行flutter pub run build_runner build时创建。 For more usage look into package page https://pub.dev/packages/build_runner#built-in-commands有关更多用法,请查看 package 页面https://pub.dev/packages/build_runner#built-in-commands

Converting Json to User object将 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);
    }
  }

given the condition you have all these packages in your pubspec.yaml鉴于您的pubspec.yaml中有所有这些包的条件

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

Note: the versions could be different, you need to get from https://pub.dev/packages注意:版本可能不同,您需要从https://pub.dev/packages 获取

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

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