flutter 书写json解析类

首先要明确json数据的类型
Map(键-值对)即Map

{
  "id":"487349",
  "name":"Pooja Bhaumik",
  "score" : 1000
}

fromJson() 方法将JSON字符串解析为java对象,Gson的toJson() 方法将Java对象转换为JSON string

总共有三种类型,第一种是单纯的基本类型int,String,第二种是对象,范类DriftBottleInfo? driftBottleInfo; 第三种是列表List? downList;

最基本的一种类型写法,类里面包含fromJson和toJson两种方法

class DownDriftBottle {
  int? downBoxId;

  DownDriftBottle.fromJson(dynamic json) {//fromJson解析服务器返回的json数据,
    downBoxId = json['down_box_id'];//然后赋值,可以把json['down_box_id']直接看作是服务器返回的那个值了
  }

//自己的数据转成json数据,Json数据是 "id":"487349",前面肯定是String类型,后面是dynamic类型,所以toJson方法是 Map类型
  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};//创建一个map
    map['down_box_id'] = downBoxId;//赋值
    return map;//返回
  }
}
基本类型加对象 
class UpDriftBottle {
  int? upBoxId; //捞到瓶子到ID
  BottleUserInfo? userInfo; //用户信息

  UpDriftBottle.fromJson(dynamic json) {
    upBoxId = json['up_box_id'];

    if (json['user_info'] != null) {//先判断不为null
      userInfo= BottleUserInfo.fromJson(json['user_info']);//不是UpDriftBottle这个类解析了,是用BottleUserInfo这个类进行解析了
    }
  }

//没用到的话可以不用写的
  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['up_box_id'] = upBoxId;
    return map;
  }
}

class BottleUserInfo {
  String? avatar;
  String? avatarThumb;
  int? birthday;
  String? nickname;
  int? sex;
  String? sign;
  int? userId;
  int? vipExpirationTime;
  int? vipLevel;
  num? dist;

  BottleUserInfo.fromJson(dynamic json) {
    avatar = json['avatar'];
    avatarThumb = json['avatar_thumb'];
    birthday = json['birthday'];
    dist = json['dist'];
    nickname = json['nickname'];
    sex = json['sex'];
    sign = json['sign'];
    userId = json['user_id'];
    vipExpirationTime = json['vip_expiration_time'];
    vipLevel = json['vip_level'];
  }
}

对象和列表

class DriftBottleSetting {
  RemainTimes? remainTimes;
  List<bottleSettingBean>? bottleSetting;//列表是范类

  DriftBottleSetting.fromJson(dynamic json) {

    if (json['remain_times'] != null) {//对象判空
      remainTimes= RemainTimes.fromJson(json['remain_times']);//用RemainTimes来解析
    }

    if (json['bottle_setting'] != null) {//判空
      bottleSetting = [];//创建一个列表
      json['bottle_setting'].forEach((v) {//for循环,解析json里面的数据,然后将值全班装进列表里面
        bottleSetting!.add(bottleSettingBean.fromJson(v));
      });
    }
  }
}

class RemainTimes {
  int? remainFishTimes;
  int? remainThrowTimes;
  int? bottleNum;

  RemainTimes.fromJson(dynamic json) {
    remainFishTimes = json['remain_fish_times'];
    remainThrowTimes = json['remain_throw_times'];
    bottleNum = json['bottle_num'];
  }
}

class bottleSettingBean {
  int? id;
  int? type;
  int? price;
  String? desc;
  bottleSettingBean.fromJson(dynamic json) {
    id = json['id'];
    type = json['type'];
    price = json['price'];
    desc = json['desc'];
  }
}

tojson的三种类型,基本类型,对象和列表,总的解析类在下面

/// down_list : [{"app_id":"string","create_time":0,"drift_bottle_id":0,"text":"string","user_id":0}]
/// my_info : {"avatar":"string","avatar_thumb":"string","birthday":0,"nickname":"string","sex":0}
/// other_info : {"avatar":"string","avatar_thumb":"string","birthday":0,"nickname":"string","sex":0}

class ReplyList {
  ReplyList({
    List<DownList>? downList,
    MyInfo? myInfo,
    OtherInfo? otherInfo,
  }) {
    _downList = downList;
    _myInfo = myInfo;
    _otherInfo = otherInfo;
  }

  ReplyList.fromJson(dynamic json) {
    if (json['down_list'] != null) {
      _downList = [];
      json['down_list'].forEach((v) {
        _downList?.add(DownList.fromJson(v));
      });
    }
    _myInfo = json['my_info'] != null ? MyInfo.fromJson(json['my_info']) : null;
    _otherInfo = json['other_info'] != null
        ? OtherInfo.fromJson(json['other_info'])
        : null;
  }

  List<DownList>? _downList;
  MyInfo? _myInfo;
  OtherInfo? _otherInfo;

  ReplyList copyWith({
    List<DownList>? downList,
    MyInfo? myInfo,
    OtherInfo? otherInfo,
  }) =>
      ReplyList(
        downList: downList ?? _downList,
        myInfo: myInfo ?? _myInfo,
        otherInfo: otherInfo ?? _otherInfo,
      );

  List<DownList>? get downList => _downList;

  MyInfo? get myInfo => _myInfo;

  OtherInfo? get otherInfo => _otherInfo;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    if (_downList != null) {
      map['down_list'] = _downList?.map((v) => v.toJson()).toList();
    }
    if (_myInfo != null) {
      map['my_info'] = _myInfo?.toJson();
    }
    if (_otherInfo != null) {
      map['other_info'] = _otherInfo?.toJson();
    }
    return map;
  }
}

/// avatar : "string"
/// avatar_thumb : "string"
/// birthday : 0
/// nickname : "string"
/// sex : 0

class OtherInfo {
  OtherInfo({
    String? avatar,
    String? avatarThumb,
    int? birthday,
    String? nickname,
    int? sex,
  }) {
    _avatar = avatar;
    _avatarThumb = avatarThumb;
    _birthday = birthday;
    _nickname = nickname;
    _sex = sex;
  }

  OtherInfo.fromJson(dynamic json) {
    _avatar = json['avatar'];
    _avatarThumb = json['avatar_thumb'];
    _birthday = json['birthday'];
    _nickname = json['nickname'];
    _sex = json['sex'];
  }

  String? _avatar;
  String? _avatarThumb;
  int? _birthday;
  String? _nickname;
  int? _sex;

  OtherInfo copyWith({
    String? avatar,
    String? avatarThumb,
    int? birthday,
    String? nickname,
    int? sex,
  }) =>
      OtherInfo(
        avatar: avatar ?? _avatar,
        avatarThumb: avatarThumb ?? _avatarThumb,
        birthday: birthday ?? _birthday,
        nickname: nickname ?? _nickname,
        sex: sex ?? _sex,
      );

  String? get avatar => _avatar;

  String? get avatarThumb => _avatarThumb;

  int? get birthday => _birthday;

  String? get nickname => _nickname;

  int? get sex => _sex;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['avatar'] = _avatar;
    map['avatar_thumb'] = _avatarThumb;
    map['birthday'] = _birthday;
    map['nickname'] = _nickname;
    map['sex'] = _sex;
    return map;
  }
}

/// avatar : "string"
/// avatar_thumb : "string"
/// birthday : 0
/// nickname : "string"
/// sex : 0

class MyInfo {
  MyInfo({
    String? avatar,
    String? avatarThumb,
    int? birthday,
    String? nickname,
    int? sex,
  }) {
    _avatar = avatar;
    _avatarThumb = avatarThumb;
    _birthday = birthday;
    _nickname = nickname;
    _sex = sex;
  }

  MyInfo.fromJson(dynamic json) {
    _avatar = json['avatar'];
    _avatarThumb = json['avatar_thumb'];
    _birthday = json['birthday'];
    _nickname = json['nickname'];
    _sex = json['sex'];
  }

  String? _avatar;
  String? _avatarThumb;
  int? _birthday;
  String? _nickname;
  int? _sex;

  MyInfo copyWith({
    String? avatar,
    String? avatarThumb,
    int? birthday,
    String? nickname,
    int? sex,
  }) =>
      MyInfo(
        avatar: avatar ?? _avatar,
        avatarThumb: avatarThumb ?? _avatarThumb,
        birthday: birthday ?? _birthday,
        nickname: nickname ?? _nickname,
        sex: sex ?? _sex,
      );

  String? get avatar => _avatar;

  String? get avatarThumb => _avatarThumb;

  int? get birthday => _birthday;

  String? get nickname => _nickname;

  int? get sex => _sex;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['avatar'] = _avatar;
    map['avatar_thumb'] = _avatarThumb;
    map['birthday'] = _birthday;
    map['nickname'] = _nickname;
    map['sex'] = _sex;
    return map;
  }
}

/// app_id : "string"
/// create_time : 0
/// drift_bottle_id : 0
/// text : "string"
/// user_id : 0

class DownList {
  DownList({
    String? appId,
    int?    createTime,
    int?    driftBottleId,
    String? text,
    int?    userId,
  }) {
    _appId = appId;
    _createTime = createTime;
    _driftBottleId = driftBottleId;
    _text = text;
    _userId = userId;
  }

  DownList.fromJson(dynamic json) {
    _appId = json['app_id'];
    _createTime = json['create_time'];
    _driftBottleId = json['drift_bottle_id'];
    _text = json['text'];
    _userId = json['user_id'];
  }

  String? _appId;
  int? _createTime;
  int? _driftBottleId;
  String? _text;
  int? _userId;

  DownList copyWith({
    String? appId,
    int? createTime,
    int? driftBottleId,
    String? text,
    int? userId,
  }) =>
      DownList(
        appId: appId ?? _appId,
        createTime: createTime ?? _createTime,
        driftBottleId: driftBottleId ?? _driftBottleId,
        text: text ?? _text,
        userId: userId ?? _userId,
      );

  String? get appId => _appId;

  int? get createTime => _createTime;

  int? get driftBottleId => _driftBottleId;

  String? get text => _text;

  int? get userId => _userId;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['app_id'] = _appId;
    map['create_time'] = _createTime;
    map['drift_bottle_id'] = _driftBottleId;
    map['text'] = _text;
    map['user_id'] = _userId;
    return map;
  }
}

基本类型直接赋值

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['avatar'] = _avatar;
    map['avatar_thumb'] = _avatarThumb;
    map['birthday'] = _birthday;
    map['nickname'] = _nickname;
    map['sex'] = _sex;
    return map;
  }

对象要先toJson再赋值,对象的那个类里面要写toJson方法,tojson基本类型
列表的要将每一项都进行tojson,然后组成list,最后再赋值

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    if (_downList != null) {
      map['down_list'] = _downList?.map((v) => v.toJson()).toList();//列表
    }
    if (_myInfo != null) {//对象
      map['my_info'] = _myInfo?.toJson();
    }
    if (_otherInfo != null) {//对象
      map['other_info'] = _otherInfo?.toJson();
    }
    return map;
  }

你可能感兴趣的:(安卓,json,flutter)