function TDJson.serialize(obj: TObject): string;
var
objType, fieldType, enumType: TRttiType;
I, oldLength, listCount: Integer;
field: TRttiField;
fieldName, fieldTypeName: string;
itemMethod: TRttiMethod;
fieldValue: TValue;
ps: PString;
pi: PInteger;
pi4: PInt64;
begin
if obj = nil then
begin
Exit;
end;
sb.Append('{');
objType := ctx.GetType(obj.ClassType);
oldLength := sb.Length;
for field in objType.GetFields do
begin
//获取字段信息,字段类型为3种类:基本类型包装类、自定义类、List
fieldName := field.Name;
fieldType := field.FieldType;
fieldTypeName := fieldType.Name;
fieldValue := field.GetValue(obj);
//判断值是否为空,因为值一旦为空,就没有向下判断的意义了
if not fieldValue.IsEmpty then
begin
//判断字段类型
case fieldValue.Kind of
tkEnumeration: ;
tkClass: ;
tkArray: ;
tkDynArray: ;
//二维指针 PString、PInteger、PInt64、PCurrency、PBoolean、
tkPointer: begin
//可以使用isEmpty判断,他内部通过FAsPointer来判断
if not fieldValue.IsEmpty then
begin
if fieldTypeName then
begin
end;
sb.Append('"').Append(fieldName).Append('":"').Append(fieldValue.AsType<PString>^).Append('"');
end;
end;
else raise Exception.Create('开发人员错误,类型有误!');
end;
end;
//判断类型
if fieldTypeName = 'PUnicodeString' then
begin
//判断值是否为nil
var wokao := value.AsType<PString>^;
end;
end;
if sb.Length <> oldLength then
begin
//说明存在Field被序列化成了JSON,去除内部Field最后的逗号
sb.Remove(sb.Length - 1, 1);
//缝上外部逗号,组成完整对象
sb.Append('}');
end else begin
//说明对象没有值移除开始的{
sb.Remove(sb.Length - 1, 1);
end;
end;
procedure TForm1.btn1Click(Sender: TObject);
var
p: TPerson;
dj: TDJson;
begin
p := TPerson.Create;
dj := TDJson.Create;
try
// p.setName('wokao');
// p.setName('wokao2');
p.setAge(10);
mmo1.Lines.Clear;
//mmo1.Lines.Add(p.getName);
mmo1.Lines.Add(p.getAge.ToString);
mmo1.Lines.Add(dj.objToJson(p));
finally
p.Free;
dj.Free;
end;
end;
标签:begin,end,field,整理,sb,fieldValue,Append
From: https://www.cnblogs.com/del88/p/18049585