如何在飞镖中创建 json 可编码 类

How to create json encodable classes in dart

此问题与thispost有关。

我尝试了以下代码:

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 个对象的列表。我希望这会转换成 json 列表 json 表示 Post class。我得到的是 "Instance of 'Post'" 字符串的列表。 所以问题是,这种语法是否不再受支持,或者我应该做些不同的事情?

看来您只能使用 toEncodable: toJson() 回退。

如果您将 Date 包装在提供 toJson() 的 class 中,则无需使用 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();
  }
}));