【问题标题】:How can I convert JSON String to Numbers?如何将 JSON 字符串转换为数字?
【发布时间】:2020-05-08 05:39:25
【问题描述】:

我遇到了一个问题,我想得到一个 JSON 响应,比如 id 为 int,但是 JSON 响应我将数字转换为字符串,有没有办法使用 Dart 将字符串转换为数字,因为我不能在 API 中进行更改?我收到了类似this 的 JSON 响应。

【问题讨论】:

  • 您可以将存储数据的方式发送到您的应用程序吗?

标签: json api flutter dart


【解决方案1】:

这可能会有所帮助,

class Employee {
  int id;
  String employeeName;
  double employeeSalary;
  int employeeAge;
  String profileImage;

  Employee({
    this.id,
    this.employeeName,
    this.employeeSalary,
    this.employeeAge,
    this.profileImage,
  });

  factory Employee.fromJson(Map<String, dynamic> json) => Employee(
        id: int.parse(json["id"]),
        employeeName: json["employee_name"],
        employeeSalary: double.parse(json["employee_salary"]),
        employeeAge: int.parse(json["employee_age"]),
        profileImage: json["profile_image"],
      );

  Map<String, dynamic> toJson() => {
        "id": id.toString(),
        "employee_name": employeeName,
        "employee_salary": employeeSalary.toString(),
        "employee_age": employeeAge.toString(),
        "profile_image": profileImage,
      };
}

【讨论】:

    【解决方案2】:

    你可以用int.parse method解析

    void main() {
      String myStringNumber = '123456';
    
      int myNumber = int.parse(myStringNumber);
    
      print(myNumber);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      相关资源
      最近更新 更多