如何覆盖在Dart中继承Map或List的对象的`toJson`

时间:2019-03-28 02:54:14

标签: json dart flutter

假设我有一个扩展列表的对象

Class MyClass extend List<int>
    test('json encoding', () {
      final Map<String, dynamic> m = <String, dynamic> {
        "a": "b",
        "c": [MyClass()],
      };
      expect(json.encode(m), '{"a":"b","c":"00"}'); 
    });

我这次考试不及格

ERROR: Expected: '{"a":"b","c":["00"]}'
  Actual: '{"a":"b","c":[[0,0]]}'
   Which: is different.
          Expected: ... :"b","c":["00"]}
            Actual: ... :"b","c":[[0,0]]}
                                  ^
           Differ at offset 14

我的问题是,如何覆盖toJson(或类似名称)以通过此测试?

1 个答案:

答案 0 :(得分:0)

经过进一步调查,在dart:conversion源代码中(截至2.2.1 https://github.com/dart-lang/sdk/blob/add5a27120b84f37d234608df716c3ac87fb4386/sdk/lib/convert/json.dart#L670起),我们无法执行此操作。我已经提交了Git问题,并提出了解决方案https://github.com/dart-lang/sdk/issues/36365#issuecomment-477450701