Skip to content

序列化

https://flutter.cn/docs/development/data-and-backend/json

小型项目

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class ServerResponse {
  bool success = false;
  String data = "";
  String reason = "";
  String message = "";

  ServerResponse.fromJson(Map<String, dynamic> json)
      : success = json['success'],
        reason = json['reason'],
        message = json['message'],
        data = json['data'];

  Map<String, dynamic> toJson() => {
        'success': success,
        'data': data,
        'reason': reason,
        'message': message,
      };
}
1
2
Map<String, dynamic> responseMap = jsonDecode(response.body);
return ServerResponse.fromJson(responseMap);

序列化 datetime

golang 序列化:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import (
    "encoding/json"
    "fmt"
    "time"
)

func main() {
    s, _ := json.Marshal(time.Now().Add(5 * time.Second))
    fmt.Printf("%s\n", s)
}

// "2009-11-10T23:00:05Z"

中型项目

https://pub.dev/packages/json_serializable/versions

1
2
3
dependencies:
  ...
  json_serializable: ^6.6.2