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

时间:2019-04-22 08:33:04

标签: json dart flutter

我将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'
  }
}

1 个答案:

答案 0 :(得分:0)

尝试

import java.util.Scanner;
import java.io.*;
public class UserData{
public static void main (String args[]) throws IOException{
    //Initialisations
    Scanner scan = new 
    Scanner(System.in);
    File UserData = new File(PATH OF FILE);
    BufferedWriter b = new BufferedWriter(new FileWriter(UserData));


    //Reader for Writer Old Data
    String text[] = new String[10];
    int count = 0;
    String path = PATH OF FILE;
    BufferedReader reader = new BufferedReader(new FileReader(path));
    String line = null;
    while ((line = reader.readLine()) != null){
        text[count] = line;
        count++;
    }

    PrintWriter pr = new PrintWriter(PATH OF FILE);    
    for (int I=0; I<text.length ; I++)
    {
        pr.println(text);
    }



    //Writer
    System.out.println("Enter your name");
    String name = scan.nextLine();
    pr.println(name);
    b.newLine();
    System.out.println("Enter your surname");
    String surname = scan.nextLine();
    pr.println(surname);
    b.newLine();
    System.out.println("Enter your age");
    int age = scan.nextInt();
    pr.println(String.valueOf(age));
    pr.close();
}
相关问题