You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中JSON转自定义对象失败求助:类型不匹配问题

解决Flutter JSON转自定义对象的问题

问题根源

你的问题出在三个核心点:

  1. 字段命名不匹配:JSON字段是大驼峰(如CardCode、DocEntry)或下划线命名(如U_Driver),但模型用小驼峰,json_serializable默认无法自动映射
  2. 类型不兼容:JSON里的DocEntry(int)、DocNum(int)、DocTotal(double)与模型定义的String类型不匹配,直接解析会导致字段值无法正确赋值
  3. 打印显示问题:默认打印对象只会输出Instance of 'order',无法查看实际字段值,需要重写toString()方法

修复步骤

1. 修改模型类,添加字段映射和类型转换

使用@JsonKey注解指定对应JSON字段名,同时自定义转换函数处理类型不兼容问题:

import 'package:json_annotation/json_annotation.dart';
  
part 'order.g.dart';
  
@JsonSerializable(explicitToJson: true)
class Order { // 类名遵循Dart大驼峰规范
    @JsonKey(name: 'CardCode')
    String? cardCode;
    @JsonKey(name: 'CardName')
    String? cardName;
    @JsonKey(name: 'DocCur')
    String? docCur;
    @JsonKey(name: 'DocEntry', fromJson: _intToString)
    String? docEntry;
    @JsonKey(name: 'DocNum', fromJson: _intToString)
    String? docNum;
    @JsonKey(name: 'DocTotal', fromJson: _doubleToString)
    String? docTotal;
    @JsonKey(name: 'DocType')
    String? docType;
    @JsonKey(name: 'U_Driver')
    String? uDriver;
    @JsonKey(name: 'U_GLINK')
    String? uGLINK;
  
    Order({this.cardCode, this.cardName, this.docCur, this.docEntry, this.docNum, this.docTotal, this.docType, this.uDriver, this.uGLINK});
  
    factory Order.fromJson(Map<String,dynamic> data) => _$OrderFromJson(data);
  
    Map<String,dynamic> toJson() => _$OrderToJson(this);

    // 自定义类型转换:int转String
    static String? _intToString(int? value) => value?.toString();
    // 自定义类型转换:double转String
    static String? _doubleToString(double? value) => value?.toString();

    // 重写toString,方便打印查看字段值
    @override
    String toString() {
      return 'Order(cardCode: $cardCode, cardName: $cardName, docEntry: $docEntry, docNum: $docNum, docTotal: $docTotal)';
    }
}

2. 重新生成序列化代码

在终端运行以下命令,让build_runner重新生成order.g.dart文件:

flutter pub run build_runner build

3. 验证解析结果

主类代码无需大幅修改,现在打印list时会输出每个对象的具体字段值:

Map<String, dynamic> orderMap = json.decode(orderJson);
List<dynamic> orderList = orderMap["value"];
  
List<Order> list = orderList.map((val) => Order.fromJson(val)).toList();
print(list); // 现在会显示每个Order对象的实际字段内容

额外提示

  • Dart类名建议用大驼峰格式,避免与潜在关键字冲突
  • 如果后续需要将String类型转回int/double,可以给@JsonKey添加toJson参数实现反向转换
  • 确保pubspec.yaml中已正确引入json_annotation、build_runner、json_serializable依赖

内容的提问来源于stack exchange,提问作者vandet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:36:38