首页 文章

使用SuperObject Delphi解析Json

提问于
浏览
0

我是JSON的新手 . 我有以下JSON数据,我不知道如何读取 transaction 对象的 idamount 值 .

{
  "errorCode": 0,
  "errorMessage": "ok",
  "platform": 4,
  "order": {
    "id": "3425",
    "description": "test api",
    "amount": 1.39,
    "currency": "RON",
    "billing": {
      "country": null,
      "county": null,
      "city": null,
      "address": "address",
      "postal_code": null,
      "first_name": "fn",
      "last_name": "ln",
      "phone": "0000000000",
      "email": "me@mobilpay.com"
    },
    "shipping": null,
    "installments": null,
    "installments_sel": null,
    "bonuspoints": null,
    "products": {
      "item": {
        "id": null,
        "name": null,
        "description": null,
        "info": null,
        "group": null,
        "amount": null,
        "currency": null,
        "quantity": null,
        "vat": null
      }
    },
  "hash": "1BB262DEE09B15ED98B777A27740E16B1F00004E",
  "transaction": {
    "id": "461512",
    "amount": 1.39,
    "currency": "RON",
    "paymentUrl": "/qp/BdKQsV1d-DsGz0e-4Bkq2e",
    "current_payment_count": null
  },
  "params": null
}

我可以阅读 errorCodeerrorMessage ,但我不知道如何访问事务 id .

这是我到目前为止的代码:

function TuDm_Athlos.ReadJson(ContentStr: TStream; var Order: TOrder): Boolean;
var
  workJson : ISuperObject;
begin
  Result := False;
  workJson := TSuperObject.ParseStream(ContentStr,False);
  Order.ErrorCode := StrToInt(workJson.S['errorCode']);
  order.ErrorMessage := workJson.S['errorMessage'];
  for workJson in workJson.O['transaction'] do
  begin
    Order.id := workJson.S['id'];
  end;
  Result := True;
end;

2 回答

  • 0

    您需要深入了解JSON对象层次结构 . 根据您在评论中发布的代码:

    function TuDm_Athlos.ReadJson(ContentStr: TStream; var Order: TOrder): Boolean;
    var
      JSON: ISuperObject;
      Order: ISuperObject;
      Trans: ISuperObject;
    begin
      Result := False;
    
      JSON := TSuperObject.ParseStream(ContentStr, False);
      if not Assigned(JSON) then
        Exit;
    
      Order := JSON.O['order'];
      if not Assigned(Order) then
        Exit;
    
      Trans := Order.O['transaction'];
      if not Assigned(Trans) then
        Exit;
    
      Order.ID := Trans.I['id'];
      Order.Amount := Trans.D['amount'];
      Order.ErrorCode := JSON.I['errorCode'];
      Order.ErrorMessage := JSON.S['errorMessage'];
    
      Result := True;
    end;
    
  • 2

    我知道这是一个非常古老的帖子,但我遇到了同样的事情 . 如果您是一名勤奋的开发人员,那么在开发过程中可能会启用范围检查和溢出检查 . 您正在使用的SuperObject版本可能使用Hash进行快速键比较,这些比较被定义为Cardinal . Hash方法假设它可以溢出Cardinal类型,但该溢出将跳转范围和溢出检查 . 要正确地执行此操作,您可以修改单位以使用Int64代替Cardinal,然后在Hash方法中屏蔽计算值以将其降低至32位,如下所示:

    h:=(h * 129 ord(k [i])$ 9e370001)和$ FFFFFFFF;

    效果相同,没有溢出 .

相关问题