Json与MsgPack格式相互转换工具函数

procedure JsonToMsgPack(AJson: TQJson; AMsgPack: TQMsgPack);
var
  I: Integer;
  AChild: TQJson;
  procedure CopyChild(AJsonChild: TQJson; AMsgPackChild: TQMsgPack);
  var
    J: Integer;
  begin
  case AJsonChild.DataType of
    jdtNull:
      AMsgPackChild.DataType := mptNull;
    jdtString:
      AMsgPackChild.AsString := AJsonChild.AsString;
    jdtInteger:
      AMsgPackChild.AsInt64 := AJsonChild.AsInt64;
    jdtFloat:
      AMsgPackChild.AsFloat := AJsonChild.AsFloat;
    jdtDateTime:
      AMsgPackChild.AsDateTime := AJsonChild.AsDateTime;
    jdtBoolean:
      AMsgPackChild.AsBoolean := AJsonChild.AsBoolean;
    jdtArray:
      begin
      AMsgPackChild.DataType := mptArray;
      J := 0;
      while J < AJsonChild.Count do
        begin
        CopyChild(AJsonChild[J], AMsgPackChild.Add);
        Inc(J);
        end;
      end;
    jdtObject:
      begin
      AMsgPackChild.DataType := mptMap;
      J := 0;
      while J < AJsonChild.Count do
        begin
        AChild := AJsonChild[J];
        CopyChild(AChild, AMsgPackChild.Add(AChild.Name));
        Inc(J);
        end;
      end;
  end;
  end;

begin
AMsgPack.Clear;
I := 0;
while I < AJson.Count do
  begin
  AChild := AJson[I];
  CopyChild(AChild, AMsgPack.Add(AChild.Name));
  Inc(I);
  end;
end;

procedure MsgPackToJson(AMsgPack: TQMsgPack; AJson: TQJson);
var
  I: Integer;
  AChild: TQMsgPack;
  procedure CopyChild(AMsgPackChild: TQMsgPack; AJsonChild: TQJson);
  var
    J: Integer;
  begin
  case AMsgPackChild.DataType of
    mptInteger:
      AJsonChild.AsInt64 := AMsgPackChild.AsInt64;
    mptNull:
      AJsonChild.ResetNull;
    mptBoolean:
      AJsonChild.AsBoolean := AMsgPackChild.AsBoolean;
    mptSingle, mptFloat:
      AJsonChild.AsFloat := AMsgPackChild.AsFloat;
    mptString, mptExtended:
      AJsonChild.AsString := AMsgPackChild.AsString;
    mptBinary:
      AJsonChild.AsBytes := AMsgPackChild.AsBytes;
    mptDateTime:
      AJsonChild.AsDateTime:=AMsgPackChild.AsDateTime;
    mptArray:
      begin
      AJsonChild.DataType := jdtArray;
      J := 0;
      while J < AMsgPackChild.Count do
        begin
        CopyChild(AMsgPackChild[J], AJsonChild.Add);
        Inc(J);
        end;
      end;
    mptMap:
      begin
      AJsonChild.DataType := jdtObject;
      J := 0;
      while J < AMsgPackChild.Count do
        begin
        AChild := AMsgPackChild[J];
        CopyChild(AChild, AJsonChild.Add(AChild.Name));
        Inc(J);
        end;
      end;
  end;
  end;

begin
AJson.Clear;
I := 0;
while I < AMsgPack.Count do
  begin
  AChild := AMsgPack[I];
  CopyChild(AChild, AJson.Add(AChild.Name));
  Inc(I);
  end;
end;

上面提供了两个函数,JsonToMsgPack 用于直接将函数内容转换到 TQMsgPack 对象,MsgPackToJson 函数执行反过程,用于将 MsgPack 的内容转换为 Json 格式。由于 MsgPack 支持的类型要比 Json 更多一点,所以这个转换会丢失一些类型的信息,这点还请注意。

要直接将 MsgPack 的内容保存到 Json 格式的字符串中,直接用 TQMsgPack.AsJson 即可。

分享到: