Parsing JSON Array in Delphi

前端 未结 1 1219
故里飘歌
故里飘歌 2021-01-29 10:53

I have a similar problem to Delphi parse JSON array or array, but the answers do not fit my need.

I have this JSON:

[
  {
    \"total\": \"9\",
    \"pa         


        
相关标签:
1条回答
  • 2021-01-29 11:46

    A nice guy from Delphipraxis DP has provided a very sophisticated solution:

         procedure TForm1.Button1Click(Sender: TObject);
         var
           DataBase: String;
           JsonArray: TJSONArray;
           ArrayElement: TJSonValue;
           RowValue: TJSonValue;
           RowItem: TJSonValue;
           keyFeatures: TJSonValue;
           FeatureItem: TJSonValue;
           FeatureList: TStringlist;
           Id: Integer;
           Index: Integer;
         begin
           Memo1.Clear;
           DataBase :=
             '[{"total":"9","page":"9","records":"99","rows":[{"id":"62316","titleId":"47243","subject":'
             + '["000607","000607_","001727"],"keyFeatures":["AI","URL"]},{"id":"66","titleId":"47243","subject":'
             + '["000607","000607_","001727"],"keyFeatures":["KK"]}],"suggestion":"90"}]';
    
           JsonArray := TJSonObject.ParseJSONValue(DataBase) as TJSONArray;
           try
             Index := 1;
             for ArrayElement in JsonArray do
             begin
               RowValue := (ArrayElement as TJSonObject).GetValue('rows');
               if RowValue is TJSONArray
               then
               begin
                 for RowItem in TJSONArray(RowValue) do
                 begin
                   RowItem.TryGetValue('id', Id);
                   keyFeatures := (RowItem as TJSonObject).GetValue('keyFeatures');
                   if keyFeatures is TJSONArray
                   then
                   begin
                     FeatureList := TStringlist.Create;
                     try
                       for FeatureItem in TJSONArray(keyFeatures) do
                         FeatureList.Add(FeatureItem.Value);
                       Memo1.Lines.Add(Format('%d: %d KeyFeatures: %s', [Index, Id, FeatureList.CommaText]));
                     finally
                       FeatureList.Free;
                     end;
                   end;
                 end;
               end;
               inc(Index);
             end;
           finally
             JsonArray.Free;
           end;
         end;
    
    0 讨论(0)
提交回复
热议问题