如何保存从TJSONObject开始的物理文件



如何从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主题的初学者

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;

最新更新