【问题标题】:How to create json encodable classes in dart如何在 dart 中创建 json 可编码类
【发布时间】:2015-07-31 08:28:02
【问题描述】:

此问题与this 帖子有关。

我尝试了以下代码:

import 'dart:convert';

/*server side Post class */
class Post {
  int post_id;
  String title;
  String description;
  DateTime posted_at;
  DateTime last_edited;
  String user;
  String editor;
  int up_votes;
  int down_votes;
  int total_votes;
  String links_to;
  List<String> tags = new List();

  Post.fromSQL(List sql_post) {
     //initialization code, unrelated.
  }

  Map toJson(){
    Map fromObject = {
      'post_id' : post_id,
      'title' : title,
      'description' : description,
      'posted_at' : posted_at,
      'last_edited' : last_edited,
      'user' : user,
      'editor' : editor,
      'up_votes' : up_votes,
      'dwon_votes' : down_votes,
      'total_votes' : total_votes,
      'links_to' : links_to,
      'tags' : tags
    };

    return fromObject;
    //I use the code below as a temporary solution
    //JSON.encode(fromObject, toEncodable: (date)=>date.toString());
  }
}

我有一个临时解决方案,但我真的很想能够做到以下几点。

JSON.encode(posts, toEncodable: (date)=>date.toString())

其中posts 是 Post 对象的列表。我希望这会转换为 Post 类的 json 表示的 json 列表。我得到的是"Instance of 'Post'" 字符串列表。 所以问题是,这种语法是否不再受支持,还是我应该做一些不同的事情?

【问题讨论】:

    标签: json dart to-json


    【解决方案1】:

    看来你只能使用toEncodable: toJson() 后备。

    如果您将 Date 包装在提供 toJson() 的类中,则无需使用 toEncodable:

    class JsonDateTime {
      final DateTime value;
      JsonDateTime(this.value);
    
      String toJson() => value != null ? value.toIso8601String() : null;
    }
    
    class Post {
      ...
      Map toJson() => {
        'post_id' : post_id,
        'title' : title,
        'description' : description,
        'posted_at' : new JsonDateTime(posted_at),
        'last_edited' : new JsonDateTime(last_edited),
        'user' : user,
        'editor' : editor,
        'up_votes' : up_votes,
        'dwon_votes' : down_votes,
        'total_votes' : total_votes,
        'links_to' : links_to,
        'tags' : tags
      };
    }
    

    或者确保您的 toEncodeable: 处理所有不受支持的类型:

    print(JSON.encode(data, toEncodable: (value) {
      if (value is DateTime) {
        return value.toIso8601String();
      } else {
        return value.toJson();
      }
    }));
    

    【讨论】:

    • 我误解了文档。我打了toEncodable 是在 toJson() 返回的对象的那些子元素上运行的,这些子元素是不可编码的。我最终通过稍微改变地图解决了这个问题:'posted_at' : posted_at.toIso8601String(), 'last_edited' : last_edited.toIso8601String(), 并完全删除了toEncodable
    • 那很好,但似乎并非如此。这当然也是一个很好的解决方案。
    • toEncodable 函数是要使用的函数,对于不可编码的对象没有其他后备。 toJson 调用只是默认的 toEncodable 函数,如果您不提供另一个函数。
    猜你喜欢
    • 2022-01-09
    • 2021-01-21
    • 1970-01-01
    • 2019-09-20
    • 2020-04-25
    • 1970-01-01
    • 2020-12-20
    • 2021-11-05
    • 2021-09-25
    相关资源
    最近更新 更多