0

I have an object eg.:

TFoo = class(TObject)
  private
    FConnection : TADOConnection;
  public
    FName    : string;
    FSurname : string;
end; 

i convert this object in a json string with ObjectToJsonString, eg.:

uses REST.Json;
// ...
var
   aFoo : TFoo;
begin
   aFoo := TFoo.create;

   Memo1.lines.text := TJson.ObjectToJsonString(aFoo);

   aFoo.free;
end;

TJson.ObjectToJsonString make a json string with both private and public variables.

i want exclude some variable like FConnection from the json string (it expose also the connection string).

Any suggestion for allow the json conversion only on the public variable?

ar099968
  • 6,963
  • 12
  • 64
  • 127
  • I don't think this is possible. Any way if you want to hide your connection string I suggest that you rather go and encode it before storing, and then decode it when loading. – SilverWarior Apr 13 '17 at 16:26
  • Related: [Delphi Rest.JSON JsonToObject only works with f variables](http://stackoverflow.com/questions/31778518/) – Remy Lebeau Apr 13 '17 at 17:45

1 Answers1

3

Use the JSONMarshalled attribute:

Attribute that specifies whether a field or type should be marshalled and unmarshalled.

If JSONMarshalledAttribute is not present in a field or type, that field or type should be marshalled and unmarshalled. If JSONMarshalledAttribute is present but is False, the marshalling and unmarshalling processes skip that field or type.

For example:

type
  TFoo = class(TObject)
  private
    [JSONMarshalled(False)]
    FConnection : TADOConnection;

  public
    FName    : string;
    FSurname : string;
  end; 

Also look at the JSONName attribute. By default, if a field name begins with an F character, marshaling strips off the F in the resulting JSON data. In your example above, this is fine, so that FName and FSurname are marshalled as Name and Surname. But this may not always be desirable, so you can use JSONName to specify your own field names in the JSON data, eg:

type
  TFoo = class(TObject)
  private
    [JSONMarshalled(False)]
    FConnection : TADOConnection;

  public
    Name    : string;
    Surname : string;

    [JSONName('FullName')]
    FullName : string;
  end; 
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • I have addedd `[JSONMarshalled(False)]` but `FConnection` is always in the json string (i use Delphi Berlin Udate 2). – ar099968 Apr 14 '17 at 06:53
  • Just an update! it works if i use `[JSONMarshalledAttribute(False)]` instead of `[JSONMarshalled(False)]` – ar099968 Apr 14 '17 at 07:03
  • 1
    @ar099968 although `Attribute` is part of the actual class name, it is [optional when used in code annotations](http://docwiki.embarcadero.com/RADStudio/en/Annotating_Types_and_Type_Members). If that is not working correctly, that is a bug that needs to be [reported to Embarcadero](http://quality.embarcadero.com). – Remy Lebeau Apr 14 '17 at 07:55