首页 > 解决方案 > 如果第一个为空,则将其他键的值存储在飞镖模型中 - Flutter

问题描述

我正在使用该json_annotation包来构建我的飞镖模型。

我有一种情况,我需要将 API 响应中的任一值存储在我的name密钥中。

API 正在返回两个密钥aliasname. 在我的模型中,我需要以这样的方式存储值,如果alias(非空)中有值,则name (模型中)将有一个alias值。否则,name(来自 API)密钥将存储在模型的name密钥中。

代码 -

import 'package:json_annotation/json_annotation.dart';

part 'nw_wealth.g.dart';

@JsonSerializable(anyMap: true)
class NwWealth {
 final int accountId;
 final String name;
 final double current;
 final double invested;
 final double gain;
 final String type;
 final double gainPercent;
 final DateTime lastUpdated;

 NwWealth(
   this.name,  // this.name should be = alias ?? name;
   this.current,
   this.invested,
   this.gain,
   this.type,
   this.gainPercent,
   this.accountId,
   this.lastUpdated,
 );

 factory NwWealth.fromJson(Map<String, dynamic> json) =>
     _$NwWealthFromJson(json);

 Map<String, dynamic> toJson() => _$NwWealthToJson(this);
}

有没有办法,我可以根据可用性将实际名称和别名存储到模型中的同一个键中?

我确实检查了JsonKey()对象。但找不到解决办法。

标签: flutterdartjson-annotation

解决方案


推荐阅读