如何自定义json_serializable库代码生成?

问题描述 投票:0回答:1

我使用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个回答
0
投票

试试这个

 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;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.