今天在网上找到了一个marshall和unmarshall的例子,将自己的定义的类,序列号json对象
uses DBXJSONReflect, DBXJSON
TPerson = class
FirstName: String;
LastName: String;
Age: Integer;
end;
序列化
procedure TForm1.Button1Click(Sender: TObject);
var
Mar: TJSONMarshal; //序列化对象
UnMar: TJSONUnMarshal; // 反序列化对象
person: TPerson; //我们自定义的对象
SerializedPerson: TJSONObject; //Json对象
begin
Mar := TJSONMarshal.Create(TJSONConverter.Create);
try
person := TPerson.Create;
try
person.FirstName := 'Nan';
person.LastName := 'Dong';
person.Age := 29;
SerializedPerson := Mar.Marshal(person) as TJSONObject;
finally
FreeAndNil(person);
end;
finally
Mar.Free;
end;
// show一下person的json对象的信息
ShowMessage(SerializedPerson.ToString);
end;
反序列化
//UnMarshalling
UnMar := TJSONUnMarshal.Create;
try
person := UnMar.UnMarshal(SerializedPerson) as TPerson;
try
// 我们用断言检查一下,unmarshal后的信息完全正确。
Assert(person.FirstName = 'Nan');
Assert(person.LastName = 'Dong');
Assert(person.Age = 29);
finally
person.Free;
end;
finally
UnMar.Free;
end;
没有评论:
发表评论