【问题标题】:How to customize json_serializable library code generation?如何自定义 json_serializable 库代码生成?
【发布时间】:2019-04-22 08:33:03
【问题描述】:

我使用json_serializable 库和firebase 作为数据库。我需要将我的数据类序列化和反序列化到 JSON。但是firebase json格式是这样的

{
  'some_id_here': {
     'title': 'some_title',
     'content': 'some_content',
     'timestamp': 'some_timestamp'
   }, ...
}

这是我的课

import 'package:json_annotation/json_annotation.dart';

part 'update.g.dart';

@JsonSerializable()

class Update {
  final String id, title, content, timestamp;

  Update({this.id, this.title, this.content, this.timestamp});

  factory Update.fromJson(Map<String, dynamic> json) => _$UpdateFromJson(json);

  Map<String, dynamic> toJson() {
    return _$UpdateToJson(this);
  }
}

那么如何自定义 toJson() 函数以便我可以反序列化

Update('ID', 'TITLE', 'CONTENT', 'TIMESTAMP');

{
  'ID': {
     'title': 'TITLE',
     'content': 'CONTENT',
     'timestamp': 'TIMESTAMP'
  }
}

【问题讨论】:

    标签: json dart flutter


    【解决方案1】:

    试试这个

     class ID {
      String title;
      String content;
      String timestamp;
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> ID = new Map<String, dynamic>();
        ID['title'] = this.title;
        ID['content'] = this.content;
        ID['timestamp'] = this.timestamp;
        return ID;
      }
    }
    

    【讨论】:

    • 因为返回的 json 不是对象列表。我应该使用Map&lt;String, ID&gt; id; 吗??
    猜你喜欢
    • 2021-01-21
    • 1970-01-01
    • 2021-02-01
    • 2016-10-03
    • 2015-11-24
    • 1970-01-01
    • 2010-11-05
    • 2018-12-29
    • 1970-01-01
    相关资源
    最近更新 更多