uses
uses
DBXJSON ,DBXJSONCommon, DBXJSONREFlect;
创建
JSONObject
{
"sn":1,
"subject":"test",
"autoSign":true
}
//var jsonObj: TJSONObject;
jsonObj := TJSONObject.Create;
try
jsonObj.AddPair('sn', TJSONNumber.Create(1));
jsonObj.AddPair('subject', TJSONString.Create('test'));
jsonObj.AddPair('autoSign', TJSONTrue.Create);
finally
jsonObj.Free;
end;
TJSONArray
{
"sn":1,
"subject":"test",
"autoSign":true,
"actions":[
{
"orderNo":1,
"type":"a"
},
{
"orderNo":2,
"type":"b"
}
]
}
//var jsonObj, actionObj1, actionObj2: TJSONObject;
//var jsonArr: TJSONArray;
jsonObj := TJSONObject.Create;
try
jsonObj.AddPair('sn', TJSONNumber.Create(1));
jsonObj.AddPair('subject', TJSONString.Create('test'));
jsonObj.AddPair('autoSign', TJSONTrue.Create);
jsonArr := TJSONArray.Create;
actionObj1 := TJSONObject.Create;
actionObj1.AddPair('orderNo', TJSONNumber.Create(1));
actionObj1.AddPair('type', TJSONString.Create('a'));
jsonArr.AddElement(actionObj1);
actionObj2 := TJSONObject.Create;
actionObj2.AddPair('orderNo', TJSONNumber.Create(2));
actionObj2.AddPair('type', TJSONString.Create('b'));
jsonArr.AddElement(actionObj2);
jsonObj.AddPair('actions', jsonArr);
finally
actionObj1.Free;
actionObj2.Free;
jsonArr.Free;
jsonObj.Free;
end;
序列化为 JSON 字符串和反序列化
通过 ToString 方法可以将 JSON 对象序列化为 JSON 字符串,使用 ParseJSONValue 方法可以将 JSON 字符串反序列化为 JSON 对象。
var
jsonObject: TJSONObject;
jsonString: string;
begin
jsonObject := TJSONObject.Create;
try
jsonObject.AddPair('name', 'John');
jsonObject.AddPair('age', TJSONNumber.Create(25));
jsonString := jsonObject.ToString; // 序列化为 JSON 字符串
// 反序列化 JSON 字符串为 JSON 对象
jsonObject := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(jsonString), 0) as TJSONObject;
finally
jsonObject.Free;
end;
end;
获取和设置 JSON 对象的值
使用
jsonObject.Get('name').JsonValue时需要注意该节点必须存在,否则报错。当不确定节点是否存在时,先判断if Assigned(jsonObject.Get('gender')) then再赋值
var
jsonObject: TJSONObject;
name: string;
age: Integer;
begin
jsonObject := TJSONObject.Create;
try
jsonObject.AddPair('name', 'John');
jsonObject.AddPair('age', TJSONNumber.Create(25));
// 获取值
name := (jsonObject.Get('name').JsonValue as TJSONString).Value; // "John"
age := (jsonObject.Get('age').JsonValue as TJSONNumber).AsInt; // 25
// 设置值
if Assigned(jsonObject.Get('name')) then
jsonObject.Get('name').JsonValue := TJSONString.Create('Alice');
if Assigned(jsonObject.Get('age')) then
jsonObject.Get('age').JsonValue := TJSONNumber.Create(30);
if Assigned(jsonObject.Get('gender')) then
jsonObject.Get('gender').JsonValue := TJSONString.Create('male');
// 添加新键值对
jsonObject.AddPair('gender', 'female');
showmessage(jsonObject.ToString);
finally
jsonObject.Free;
end;
end;
924

被折叠的 条评论
为什么被折叠?



