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;