【问题标题】:如何保存从 TJSONObject 开始的物理文件?
【发布时间】:2022-01-23 04:50:36
【问题描述】:

如何从我的 JSONObject3 对象开始将物理 .json 文件保存到我的 C:\ 驱动器?

procedure CreateJSON;
var
  JSONObject2, JSONObject3: TJSONObject;
  JSONValue1, JSONValue2: TJSONValue;
  JSONArray: TJSONArray;
  JSONString1, JSONString2: TJSONString;
  AText, BText: string;
  mStringStream:      TStringStream;
begin
  JSONObject2 := TJSONObject.Create;
  JSONObject3 := TJSONObject.Create;
  JSONArray := TJSONArray.Create;
  try   
    AText := 'Name';
    BText := '"Charles"';
    JSONString2 := TJSONString.Create(AText);
    JSONValue2 :=  TJSONObject.ParseJSONValue(BText);

    JSONObject2.AddPair(JSONString2, JSONValue2);   
    JSONArray.Add(JSONObject2);    
    JSONObject3.AddPair('People', JSONArray);

    mStringStream := TStringStream.Create('', TEncoding.UTF8);
    // m_StringStream.LoadFromStream(JSONObject3.ToString); <---ERROR
    mStringStream.SaveToFile('people.json');
  finally
    JSONObject3.Free;
  end;
end;

谢谢,我是json主题的初学者

【问题讨论】:

    标签: json delphi delphi-xe4


    【解决方案1】:

    TJSONObject 没有任何流媒体支持,但它确实有几个To...() 输出方法(ToBytes()ToJSON()ToString())。任何这些方法的输出都可以写入文件,例如使用TFile.WriteAll...() 方法(WriteAllBytes()WriteAllText())。

    试试这个:

    uses
      ...,
      Data.DBXJSON, // use System.JSON in XE6+
      System.IOUtils,
      System.SysUtils;
    
    procedure CreateJSON;
    var
      JSONObject, JSONObject2: TJSONObject;
      JSONValue: TJSONValue;
      JSONArray: TJSONArray;
      AText, BText: string;
    begin
      JSONObject := TJSONObject.Create;
      try   
        AText := 'Name';
        BText := '"Charles"';
    
        JSONValue := TJSONObject.ParseJSONValue(BText);
        if JSONValue <> nil then
        try
          JSONObject.AddPair(AText, JSONValue);
        except
          JSONValue.Free;
          raise;
        end;
    
        JSONArray := TJSONArray.Create;
        try
          JSONObject2 := TJSONObject.Create;
          try
            JSONArray.Add(JSONObject2);
          except
            JSONObject2.Free;
            raise;
          end;
          JSONObject.AddPair('People', JSONArray);
        except
          JSONArray.Free;
          raise;
        end;
    
        TFile.WriteAllText('people.json', JSONObject.ToJSON, TEncoding.UTF8);
      finally
        JSONObject.Free;
      end;
    end;
    

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-15
      • 2016-07-25
      相关资源
      最近更新 更多