1

I'm trying to use the JSON features of Delphi 10.3 but I can't get my around UPDATING a value in a JSON Object. AddPair creates a NEW pair, even if the name already exists and I find no way to set the value as all functions/properties are read-only...

Do I really have to delete the pair and create it?

Wolfgang Bures
  • 509
  • 4
  • 12
  • 1
    Does this answer your question? [Delphi XE7: How to change a JSON value using System.JSON (versus SuperObject)](https://stackoverflow.com/questions/33426576/delphi-xe7-how-to-change-a-json-value-using-system-json-versus-superobject) – Remy Lebeau Apr 03 '20 at 16:26
  • 1
    Also related: [Update TJSONArray](https://stackoverflow.com/questions/53635025/) – Remy Lebeau Apr 03 '20 at 16:26

1 Answers1

3

Before Rio, I colud do something like this:

Procedure AddValue(pObj: TJSONObject; pName: String; pJSONValue: TJSONValue);
var vJsonPair: TJsonPair;
begin
  vJsonPair:= pObj.Get(pName);

  if Assigned(vJsonPair) then
     begin
        //preserving the place  
        vJsonPair.JsonValue.free;
        vJsonPair.JsonValue:= pJSONValue;
     end
  else
    pObj.AddPair(pName, pJSONValue);
end;

But, with Rio+, I must to do this:

Procedure AddValue(pObj: TJSONObject; pName: String; pJSONValue: TJSONValue);
var vJsonPair: TJsonPair;
begin
  vJsonPair:= pObj.Get(pName);

  if Assigned(vJsonPair) then
     begin
       //putting the pair at the end of the object 
       pObj.RemovePair(pName);
       pObj.AddPair(pName, pJSONValue);
     end
  else
    pObj.AddPair(pName, pJSONValue);
end;

So, with Delphi System.JSON, you have to check if the pair exists to replace it. And from Rio, you have to delete and create the pair again

GatoSoft
  • 106
  • 1
  • 3
  • I upgraded from Delphi 10.1 Berlin to 11 Alexandria. You can simply remove `vJsonPair.JsonValue.free;` line and it works. – akaya May 10 '22 at 08:11