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

Protobuf解析含null的字符串数组报错 Flutter端如何规避异常

Flutter Protobuf解析含null字符串数组的解决方案

问题核心

标准Protobuf中repeated string类型的JSON解析规则不允许数组内出现null值,因此解析包含null的字符串数组时会直接抛出异常。

可选解决方案

方案1:使用google.protobuf.Value定义字段

引入Protobuf官方的Struct扩展类型,可兼容任意JSON值类型,定义如下:

// 头部引入依赖
import "google/protobuf/struct.proto";

// 修改字段定义
repeated google.protobuf.Value value_array = 6;

Flutter端解析后转换为字符串数组的逻辑:

List<String> getValueArray(List<Value> protoArray) {
  return protoArray.map((item) {
    if (item.hasNullValue()) return "";
    return item.stringValue ?? "";
  }).toList();
}

方案2:使用proto3 optional语法

Protobuf 3.12及以上版本支持optional修饰字符串类型,可接收null值,定义更轻量化:

repeated optional string value_array = 6;

解析后直接判断元素是否为null,统一替换为空字符串即可。

方案3:全局预处理JSON(无需修改proto定义)

写一个通用的JSON预处理函数,递归替换所有数组内的null值为空字符串,所有接口解析前调用即可,无需单独调整每个接口的逻辑:

import 'dart:convert';

Map<String, dynamic> preprocessNullInArrays(String jsonStr) {
  final jsonData = jsonDecode(jsonStr);
  void recursiveReplace(dynamic node) {
    if (node is Map) {
      node.forEach((_, value) => recursiveReplace(value));
    } else if (node is List) {
      for (int i = 0; i < node.length; i++) {
        if (node[i] == null) {
          node[i] = "";
        } else {
          recursiveReplace(node[i]);
        }
      }
    }
  }
  recursiveReplace(jsonData);
  return jsonData;
}

// 解析时调用示例
final yourProto = YourProtoMessage.fromJson(preprocessNullInArrays(response.body));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:18:03