System.JSON.BSON.pas
这可是DELPHI官方支持BSON的单元。是DELPHI10开始增加的。
TBsonWriter,TBsonReader 分别用于BSON序列和还原。
uses System.JSON.BSON, System.JSON.Writers, System.JSON.Builders; procedure BSONWriterSample; var Builder: TJSONObjectBuilder; //To use the built-in JSON builder BytesStream: TBytesStream; //To create the BSON document as a byte stream Writer: TBsonWriter; //A BSON writer Bytes: TBytes; //To contain the bytes from the byte stream begin BytesStream := TBytesStream.Create; Writer := TBsonWriter.Create(BytesStream); Builder := TJSONObjectBuilder.Create(Writer); try Builder .BeginObject .BeginArray('colors') .BeginObject .Add('name','red') .Add('hex','#f00') .EndAll; Bytes := BytesStream.Bytes; SetLength(Bytes, BytesStream.Size); //Bytes contains the BSON document. Memo1.text := Bytes2String(Bytes); //To see the representation of the BSON document in a TMemo, passing the Bytes var that contains the BSON document. finally BytesStream.free; Writer.free; Builder.free; end; end;
{ "colors": [ { "name": "red", "hex": "#f00" } ] }
function Bytes2String(const ABytes: TBytes): string; var I: Integer; begin Result := ''; for I := Low(ABytes) to High(ABytes) do if I = 0 then Result := IntToHex(ABytes[I], 2) else Result := Result + '-' + IntToHex(ABytes[I], 2); end;
序列JSON对象为BSON:
uses System.JSON.BSON, System.JSON.Writers, System.JSON.Readers, System.JSON.Builders; procedure JSONtoBSON; var SR: TStringReader; //A String Reader JsonReader: TJsonTextReader; //A JSON text Reader BsonWriter: TBsonWriter; // A BSON writer Stream: TBytesStream; //To create the BSON document as a byte stream Bytes: TBytes; //To contain the bytes from the byte stream begin SR := TStringReader.Create(Memo1.Text); //It gets the JSON object as a string from a TMemo. JsonReader := TJsonTextReader.Create(SR); Stream := TBytesStream.Create; BsonWriter := TBsonWriter.Create(Stream); try BsonWriter.WriteToken(JsonReader); //It gets the JSON object as an argument and analize the object token by token. Stream.Position := 0; Bytes := Stream.Bytes; SetLength(Bytes, Stream.Size); Memo2.Text := Bytes2String(Bytes); //It shows the String representation of the BSON document in a TMemo. finally SR.free; JsonReader.free; Stream.free; BsonWriter.free; end; end;