如何在dart中创建json可编码类

如何在dart中创建json可编码类,json,dart,to-json,Json,Dart,To Json,这个问题与邮政有关 我尝试了以下代码: 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;

这个问题与邮政有关

我尝试了以下代码:

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());
  }
}
其中
posts
是Post对象的列表。我希望将其转换为Post类的json表示的json列表。我得到的是一个
“Post”实例
字符串列表。

所以问题是,这种语法是否不再受支持,或者我应该做些不同的事情?

似乎您只能使用
来编码:
toJson()
回退

如果将日期包装在提供
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
  };
}
或者,确保您的
ToEncodable:
处理所有不受支持的类型:

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(),
并将
完全删除为encodable
。这很好,但似乎不是这样。当然,这也是一个很好的解决方案。
toencoable
函数就是要使用的函数,对于不可编码的对象没有其他的回退。
toJson
调用只是默认的
toEncodable
函数,如果您不提供另一个函数的话。
print(JSON.encode(data, toEncodable: (value) {
  if (value is DateTime) {
    return value.toIso8601String();
  } else {
    return value.toJson();
  }
}));