delphi和go以及其他语言基于结构的数据序列和还原

delphi和go以及其他语言基于结构的数据序列和还原

数据序列基于结构,是跨语言、平台能够实现数据标准的基础。

GO基于结构的序列

// test2 project main.go
package main

import (
	"encoding/json"
	"fmt"

	"github.com/golang/protobuf/proto"
)

func main() {
	var dw Tunit
	dw.Unitid = "1"
	dw.Unitname = "个"
	var dw2 Tunit
	dw2.Unitid = "2"
	dw2.Unitname = "双"
	var dws TunitArray
	dws.Tunits = append(dws.Tunits, &dw)
	dws.Tunits = append(dws.Tunits, &dw2)
	//json序列
	b, _ := json.Marshal(dws)
	fmt.Println(string(b)) //{"tunits":[{"unitid":"1","unitname":"个"},{"unitid":"2","unitname":"双"}]}
	//json还原
	var s TunitArray
	json.Unmarshal(b, &s)
	fmt.Println(s)
	for _, v := range s.Tunits {
		fmt.Println(v.Unitid)
	}
	//protobuf序列
	b2, _ := proto.Marshal(&dws)
	fmt.Println(string(b2))
	//protobuf还原
	var ss TunitArray
	proto.Unmarshal(b2, &ss)
	fmt.Println(ss)
	for _, v := range ss.Tunits {
		fmt.Println(v.Unitname)
	}
}

  DELPHI基于结构的序列

procedure TForm1.Button4Click(Sender: TObject);
//record2json
begin
  SetLength(users, 2);
  var user: TUser;
  user.name := '王五';
  user.age := 1;
  users[0] := user;
  var user2: TUser;
  user2.name := '赵六';
  user2.age := 2;
  users[1] := user2;
  var serial: TJsonSerializer := TJsonSerializer.Create;
  Memo1.Text := serial.Serialize<TArray<TUser>>(users);    //[{"name":"王五","age":1},{"name":"赵六","age":2}]
  serial.Free;
end;

procedure TForm1.Button5Click(Sender: TObject);
//json2record
begin
  var serial: TJsonSerializer := TJsonSerializer.Create;
  users := serial.Deserialize<TArray<TUser>>(Memo1.Text);
  for var user: TUser in users do
    memo1.Lines.Add(user.name);
  serial.Free;
end;

  

procedure TForm1.Button1Click(Sender: TObject);
begin
  var t: TTablesRecord;
  SetLength(t.Goodss, 1);
  SetLength(t.Unitss, 1);
  t.Goodss[0].Goodsid := '1';
  t.Goodss[0].Goodsname := '商品';
  t.Unitss[0].Unitid := '1';
  t.Unitss[0].Unitname := '单位';
  //序列
  var b: tbytes := TgoProtocolBuffer.Serialize<TTablesRecord>(t);
  //还原
  var t2: TTablesRecord;
  TgoProtocolBuffer.Deserialize<TTablesRecord>(t2, b);
  Memo1.Lines.Add(t2.Goodss[0].Goodsid);
  Memo1.Lines.Add(t2.Goodss[0].Goodsname);
  Memo1.Lines.Add(t2.Unitss[0].Unitid);
  Memo1.Lines.Add(t2.Unitss[0].Unitname);
end;

  

posted @ 2022-07-21 17:46  delphi中间件  阅读(281)  评论(0编辑  收藏  举报