简体   繁体   中英

How do parse json to object and use in another class

How do parse JSON to object and use in another class? For example, I get a response and create 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 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?

hi kakajan the way I use data across dart file is. Step 1: Create a Global.dart (Dont declare a class within it), declare the variables here that is

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

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: )

Use build_runner package to generate your json parse methods and use to convert json to object and vice versa.

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 . For more usage look into package page https://pub.dev/packages/build_runner#built-in-commands

Converting Json to User 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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