【问题标题】:How to take int from json and parse it as bool in dart?如何从 json 中获取 int 并将其解析为 dart 中的 bool?
【发布时间】:2020-05-06 18:13:50
【问题描述】:

我的模型如下:

class Abc extends Model {
  int playful;

  Abc({this.playful}) : super(id);

  Abc.fromJson(Map<String, dynamic> json) : this(playful: json['playful']);

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['playful'] = this.playful;
    return data;
  }
}

我从json 获得整数值playful(它是1 或0),但我想在我的应用程序中将它用作boolean(在应用程序中接收为bool,但发送为@987654326 @ 在数据库中)。如何实现?

【问题讨论】:

    标签: json parsing flutter dart orm


    【解决方案1】:

    试试这个,

    class Abc extends Model {
      bool playful;
    
      Abc({this.playful}) : super(id);
    
      Abc.fromJson(Map<String, dynamic> json) : this(playful: json['playful'] == 1);
    
      Map<String, dynamic> toJson() {
        final data = <String, dynamic>{};
        data['playful'] = this.playful ? 1 : 0;
        return data;
      }
    }
    

    【讨论】:

    • 工作就像一个魅力!完美描述。 :) 谢谢。
    【解决方案2】:

    据我所知,Dart 没有任何解析布尔值的函数或方法。所以我会在这个类中创建一个私有函数,它会返回给定整数的布尔值。

    bool parseBool(int integer) {
      return integer == 1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-08
      • 2021-07-21
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多