1

I really love the way mORMot / Synopse has implemented the handling of JSON, especially the way you can use the JSON elements in your code (like MyString := myjson.name). This is very intuitive and useful in wrapping objects which only have one Variant (JSON) with state which we access through getters/setters, like below:

  TMyObject = class
  private
    FState: Variant;

    function GetName: String;
  public
    constructor Create(AJson: Variant);

    property Name: String read GetName;
  end;

  function TMyObject.GetName: String;
  begin
    Result := FState.name;
  end;

It is really powerful, but I would like to get the 'default' variant value if an element is not found in the corresponding JSON document (so, above example should return an empty string if 'name' is not present).

I don't want to use NullStrictConvert, because that is not thread safe and influences the rest of our program. Of course I could check VarIsNull(FState.name), but then I have to do this for each element and I prefer not to have this extra boilerplate.

Any suggestions?

Laurens
  • 153
  • 1
  • 10

1 Answers1

2

When you unserialize some JSON into an object, the missing fields are left untouched IIRC.

So you can just set the fields to their default values before unserializing the JSON.

One way of doing it is to inherit from TSynPersistent and override the Create constructor and set default value(s).

Edit: You may use a TDocVariantData instead of variant, and call GetAsRawUTF8() and such methods which return false if the property is not existing.

Arnaud Bouchez
  • 40,947
  • 3
  • 66
  • 152