Flutter 解析JSON json_serializable

先记录下这个地址后面会用到:
https://caijinglong.github.io/json2dart/index_ch.html

image.png

首先新建一个test 里面的的类方法 是上面链接生成的
注意
import 'package:json_annotation/json_annotation.dart';
part 'Test_bean.g.dart';
这两行
part 'Test_bean.g.dart'; 引入会报错
因为没有执行
flutter packages pub run build_runner build

image.png

引入依赖
json_annotation: ^4.4.0

json_serializable: ^6.1.1
build_runner: ^2.1.5


image.png
import 'package:json_annotation/json_annotation.dart';

part 'Test_bean.g.dart';


@JsonSerializable()
class Test_bean extends Object {

  @JsonKey(name: 'name')
  String name;

  @JsonKey(name: 'age')
  int age;

  @JsonKey(name: 'contents')
  List contents;

  Test_bean(this.name,this.age,this.contents,);

  factory Test_bean.fromJson(Map srcJson) => _$Test_beanFromJson(srcJson);

  Map toJson() => _$Test_beanToJson(this);

}


@JsonSerializable()
class Contents extends Object {

  @JsonKey(name: 'content')
  String content;

  Contents(this.content,);

  factory Contents.fromJson(Map srcJson) => _$ContentsFromJson(srcJson);

  Map toJson() => _$ContentsToJson(this);

}



Test.json

{
  "name": "8888",
  "age": 12,
  "contents": [
    {
      "content": "1"
    },
    {
      "content": "2"
    }
  ]
}

pubspec.yaml


image.png

data_services.dart
这里开始解析本地json

import 'package:flutter/services.dart';
import 'package:flutter_work/entity/Test_bean.dart';
import 'dart:convert';
import 'dart:async';
import 'package:flutter_work/entity/home_bean.dart';

Future _loadAssets() async {
  return await rootBundle.loadString('assets/Test.json');
}
Future loadData() async{
  String jsonString=await _loadAssets();
  final jsonResponse=json.decode(jsonString);
  Test_bean entity=Test_bean.fromJson(jsonResponse);
  print(entity.name);

  print(entity.contents[0].content);
}

执行 loadData() OK

你可能感兴趣的:(Flutter 解析JSON json_serializable)