json如何转换为bson

function TMyMongoDbClass.JsonToBson(code:string;obj: tjsonvalue): tbson;
var
b:tbson;
jv:tjsonvalue;
buffer:tbsonbuffer;
function BL_json(curbuf:tbsonbuffer;pname:string;tobj:tjsonvalue):tbson;
var
i:integer;
p:tjsonpair;
pn,s1,s2:string;
ja:tjsonarray;
o:tjsonobject;
tb:tbson;
begin
//{name:001,arr:[{obj:1},{obj:2}]}
if tobj is tjsonnumber then
begin
s2:=tobj.ToString;
if s2.StartsWith('"') then
delete(s2,1,1);
if s2.EndsWith('"') then
delete(s2,length(s2),1);

curbuf.append(pname,strtofloat(s2));
exit;
end;
if tobj is tjsonstring then
begin
s2:=tobj.ToString;
if s2.StartsWith('"') then
delete(s2,1,1);
if s2.EndsWith('"') then

delete(s2,length(s2),1);
curbuf.append(pname,s2);
exit;
end;
if tobj is tjsontrue then
begin
curbuf.append(pname,true);
exit;
end;
if tobj is tjsonfalse then
begin
curbuf.append(pname,false);
exit;
end;


if tobj is tjsonarray then
begin
ja:=tobj as tjsonarray;
curbuf.startArray(pname);
for i := 0 to ja.count-1 do
begin
//tb:=bl_json(tbuf,ja.Items[i]);
BL_Json(curbuf,'',ja.Items[i]);
end;
curbuf.finishObject;
end;
if tobj is tjsonobject then
begin
//{name:001,arr:[{obj:1},{obj:2}]}
buffer.startObject(pname);
o:=tobj as tjsonobject;
for i := 0 to o.Count-1 do
begin
s1:=o.Pairs[i].JsonString.ToString;
delete(s1,1,1);
delete(s1,length(s1),1);

if o.Pairs[i].JsonValue is tjsonnumber then
begin
s2:=o.Pairs[i].jsonValue.ToString;
if s2.StartsWith('"') then
delete(s2,1,1);
if s2.EndsWith('"') then
delete(s2,length(s2),1);
curbuf.append(s1,strtofloat(s2));
continue;
end;
if o.Pairs[i].JsonValue is tjsonstring then
begin
s2:=o.Pairs[i].JsonValue.ToString;
if s2.StartsWith('"') then
delete(s2,1,1);
if s2.EndsWith('"') then

delete(s2,length(s2),1);
curbuf.append(s1,s2);
continue;
end;
if o.Pairs[i].JsonValue is tjsontrue then
begin
curbuf.append(s1,true);
continue;
end;
if o.Pairs[i].JsonValue is tjsonfalse then
begin
curbuf.append(s1,false);
continue;
end;


BL_Json(curbuf,s1,o.Pairs[i].JsonValue);
end;
curbuf.finishObject;
end;

 

end;

begin
//解析json
buffer:=tbsonbuffer.Create;

BL_json(buffer,'code',obj);
b:=buffer.finish;
exit(b);
end;

转载于:https://www.cnblogs.com/HuiLove/p/4513862.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值