首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

将JSON反序列化为类型化对象数组(Delphi 11)

在Delphi 11中,将JSON反序列化为类型化对象数组的过程可以通过使用Delphi自带的TJSONMarshal和TJSONUnmarshal类来实现。

首先,需要定义一个与JSON数据结构对应的类型化对象。假设我们有一个JSON数组,每个对象包含两个属性:name和age。

代码语言:txt
复制
type
  TPerson = class
  private
    FName: string;
    FAge: Integer;
  public
    property Name: string read FName write FName;
    property Age: Integer read FAge write FAge;
  end;

接下来,我们可以使用TJSONUnmarshal类将JSON数据反序列化为类型化对象数组。

代码语言:txt
复制
uses
  System.JSON, System.JSON.Types;

function DeserializeJSONToArray(jsonStr: string): TArray<TPerson>;
var
  jsonArray: TJSONArray;
  jsonValue: TJSONValue;
  jsonPair: TJSONPair;
  person: TPerson;
  i: Integer;
begin
  jsonArray := TJSONObject.ParseJSONValue(jsonStr) as TJSONArray;
  SetLength(Result, jsonArray.Count);
  
  for i := 0 to jsonArray.Count - 1 do
  begin
    jsonValue := jsonArray.Items[i];
    if jsonValue is TJSONObject then
    begin
      person := TPerson.Create;
      for jsonPair in (jsonValue as TJSONObject) do
      begin
        if jsonPair.JsonString.Value = 'name' then
          person.Name := jsonPair.JsonValue.Value
        else if jsonPair.JsonString.Value = 'age' then
          person.Age := jsonPair.JsonValue.Value.ToInteger;
      end;
      Result[i] := person;
    end;
  end;
end;

以上代码通过解析JSON字符串并逐个遍历数组中的对象,将数据转换为类型化对象数组。

使用示例:

代码语言:txt
复制
var
  jsonStr: string;
  personArray: TArray<TPerson>;
  person: TPerson;
begin
  // 假设jsonStr包含了一段JSON数组字符串

  personArray := DeserializeJSONToArray(jsonStr);
  
  for person in personArray do
  begin
    // 处理每个人的数据
    ShowMessage(Format('Name: %s, Age: %d', [person.Name, person.Age]));
  end;
end;

这样,你就可以成功地将JSON反序列化为类型化对象数组了。

推荐的腾讯云相关产品和产品介绍链接地址:

  • 腾讯云云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 腾讯云对象存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯云数据库(TencentDB):https://cloud.tencent.com/product/tencentdb
  • 腾讯云人工智能(AI):https://cloud.tencent.com/product/ai
  • 腾讯云物联网开发平台(IoT Hub):https://cloud.tencent.com/product/iothub
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

18分41秒

041.go的结构体的json序列化

领券