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

如何让TJson.ObjectToJsonString()正确序列化TNullableInteger字段?

解决TJson.ObjectToJsonString序列化TNullableInteger字段的问题

方法一:自定义JSON拦截器修正类型输出

默认的TJSONInterceptor会把TNullableInteger的有效值序列化为字符串,你可以自定义拦截器,强制将有值的TNullableInteger输出为数字类型:

type
  TNullableIntegerInterceptor = class(TJSONInterceptor)
  public
    function GetPropValue(Instance: TObject; PropInfo: PPropInfo;
      var JSONValue: TJSONValue): Boolean; override;
  end;

function TNullableIntegerInterceptor.GetPropValue(Instance: TObject;
  PropInfo: PPropInfo; var JSONValue: TJSONValue): Boolean;
var
  NullableInt: TNullableInteger;
begin
  Result := inherited;
  // 匹配TNullableInteger类型的属性
  if PropInfo^.PropType^.Name = 'TNullableInteger' then
  begin
    NullableInt := TNullableInteger(GetOrdProp(Instance, PropInfo));
    if NullableInt.HasValue then
      // 有值时输出数字类型
      JSONValue := TJSONNumber.Create(NullableInt.Value)
    else
      // 无值时输出null
      JSONValue := TJSONNull.Create;
    Result := True;
  end;
end;

在你的类属性上指定这个自定义拦截器:

type
  TMyClass = class
  private
    FNullableId: TNullableInteger;
  public
    [JsonReflect(ctString, rtString, TNullableIntegerInterceptor)]
    property NullableId: TNullableInteger read FNullableId write FNullableId;
  end;

方法二:手动构建JSON对象(无需拦截器)

如果不想依赖拦截器,可以直接手动遍历属性构建JSON,完全控制序列化逻辑:

function SerializeMyClass(Obj: TMyClass): string;
var
  JSONObj: TJSONObject;
begin
  JSONObj := TJSONObject.Create;
  try
    if Obj.NullableId.HasValue then
      JSONObj.AddPair('NullableId', TJSONNumber.Create(Obj.NullableId.Value))
    else
      JSONObj.AddPair('NullableId', TJSONNull.Create);
    // 其他属性同理添加
    Result := JSONObj.ToString;
  finally
    JSONObj.Free;
  end;
end;

这两种方法都能让TNullableInteger字段在有值时序列化为数字类型,无值时输出null,符合JSON的类型规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:24:58