JSONObject 子项上的 TJSONUnMarshal 回复器

问题描述 投票:0回答:0

我试图弄清楚 Reverter 是如何为 TJSONUnMarshal 对象工作的。我有一个基于一些 JSON 的 TJSONObject,它包含以下属性:

{
  "header": {
    "id": 39,
    "relation": "Test Company",
    "relationId": "00214",    
    "changeDate": "2023-02-22 15:18:30",
  },
  "lines": {
    "lines": []
  }
}

还有一个名为 TCustomer 的相应类,其中包含属性 TCustomerHeader 和 TCustomerLines。这是我尝试在以下位置执行 UnMarshal(基于 Rest.JSONReflect 使用)的地方:

procedure TCustomer.LoadFromJSonObj(objJSON: TJSONObject);
var
  objUnMarshaller: TJSONUnMarshal;
begin
  objUnMarshaller := TJSONUnMarshal.Create();
  try
    objUnMarshaller.RegisterReverter(TCustomer, 'header.changeDate',
      procedure(Data: TObject; Field: string; Arg: string)
      begin
        TCustomer(Data).FHeader.ChangeDate := EncodeDateTime(StrToInt(Copy(Arg, 1, 4)), StrToInt(Copy(Arg, 6, 2)), StrToInt(Copy(Arg, 9, 2)), StrToInt(Copy(Arg, 12, 2)), StrToInt(Copy(Arg, 15, 2)), StrToInt(Copy(Arg, 18, 2)), StrToInt(Copy(Arg, 21, 3)));
      end);

     objUnMarshaller.CreateObject(TCustomer, objJSON, self);
  finally
     objUnMarshaller.Free;
  end;
end;

但是 CreateObject 失败的原因似乎是 changeDate 日期时间,这就是为什么我想使用 Reverter 但我无法弄清楚如何激活它,因为 changeDate 在不同的类(TCustomerHeader)中。

甚至可以将 Reverter 设置为某些 JSON 中的子项吗?

当我尝试仅对 TCustomerHeader 类执行 Unmarshal 时,如果我将字段设置为“changeDate”,则会触发回复器,所以我知道它有效。

当我尝试在 Reverter 上设置标头的类时,它不会转到我的断点。

    procedure TCustomer.LoadFromJSonObj(objJSON: TJSONObject);
var
  objUnMarshaller: TJSONUnMarshal;
begin
  objUnMarshaller := TJSONUnMarshal.Create();
  try
    objUnMarshaller.RegisterReverter(TCustomerHeader, 'changedDate',
      procedure(Data: TObject; Field: string; Arg: string)
      begin
        TCustomerHeader(Data).ChangeDate := EncodeDateTime(StrToInt(Copy(Arg, 1, 4)), StrToInt(Copy(Arg, 6, 2)), StrToInt(Copy(Arg, 9, 2)), StrToInt(Copy(Arg, 12, 2)), StrToInt(Copy(Arg, 15, 2)), StrToInt(Copy(Arg, 18, 2)), StrToInt(Copy(Arg, 21, 3)));
      end);

     objUnMarshaller.CreateObject(TCustomer, objJSON, self);
  finally
     objUnMarshaller.Free;
  end;
end;
json delphi unmarshalling
© www.soinside.com 2019 - 2024. All rights reserved.