Delphi 11如何将JSON反序列化为强类型对象数组
解决方案
核心原因:Delphi 自带的 TJson.JsonToObject 泛型方法不支持自定义的非泛型动态数组类型作为泛型参数,你之前定义的TSongsterList = array of TSongsterResponse属于非泛型动态数组别名,因此无法直接传入完成编译。
方案1(适用于Delphi XE7及以上版本)
直接使用内置泛型数组类型TArray<TSongsterResponse>作为泛型参数即可:
interface uses ..., System.Generics.Collections; // 按需引用 type TSongsterResponse = class public id: integer; title: string; end; // 也可以用泛型别名定义数组类型,后续使用更方便 TSongsterList = TArray<TSongsterResponse>; implementation procedure Sample(AJson: string); var FSomething: TSongsterList; begin FSomething := TJson.JsonToObject<TSongsterList>(RESTResponse1.Content); // 也可以直接写成 TJson.JsonToObject<TArray<TSongsterResponse>>(RESTResponse1.Content); // 注意:使用完毕后需要遍历释放数组内所有对象,避免内存泄漏 end;
方案2(兼容旧版本+内存管理更便捷)
使用泛型列表TList<TSongsterResponse>作为反序列化目标类型,后续内存释放更简单:
interface uses ..., System.Generics.Collections; type TSongsterResponse = class public id: integer; title: string; end; TSongsterList = TList<TSongsterResponse>; implementation procedure Sample(AJson: string); var FSomething: TSongsterList; begin FSomething := TJson.JsonToObject<TSongsterList>(RESTResponse1.Content); // 使用完毕后直接调用Free即可同时释放列表实例和所有元素对象 FSomething.Free; end;
内容的提问来源于stack exchange,提问作者Larry Lustig
相关产品推荐
相关产品推荐

