jsondelphidelphi-xe4

How do I save a physical file starting from a TJSONObject?


How do I save a physical .json file to my C: \ drive starting from my JSONObject3 object?

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;

Thank you, I am a beginner with the json topic


Solution

  • TJSONObject does not have any streaming support, but it does have several To...() output methods (ToBytes(), ToJSON() ToString()). The output of any of those methods can be written to a file, such as with TFile.WriteAll...() methods (WriteAllBytes(), WriteAllText()).

    Try this instead:

    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;