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

Luk*_*asz 3 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;
  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());
  }
}
Run Code Online (Sandbox Code Playgroud)

我有一个临时解决方案,但我真的希望能够执行以下操作。

JSON.encode(posts, toEncodable: (date)=>date.toString())
Run Code Online (Sandbox Code Playgroud)

其中posts是 Post 对象的列表。我希望它能转换为 Post 类的 json 表示形式的 json 列表。我得到的是一个字符串列表"Instance of 'Post'"。所以问题是,这种语法是否不再受支持,或者我应该采取不同的做法?

Gün*_*uer 5

看来你只能使用toEncodable: OR后备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
  };
}
Run Code Online (Sandbox Code Playgroud)

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

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