Watch, Follow, &
Connect with Us

For forums, blogs and more please visit our
Developer Tools Community.


Welcome, Guest
Guest Settings
Help

Thread: Change a TJSONObject value?


This question is answered.


Permlink Replies: 1 - Last Post: Jun 1, 2017 8:37 PM Last Post By: Francesco Marano
Brian Wheatley

Posts: 60
Registered: 2/5/01
Change a TJSONObject value?  
Click to report abuse...   Click to reply to this thread Reply
  Posted: Jun 1, 2017 6:55 PM
Hello,

I have an application that is passing JSON objects to the server. I am able to convert them to TJSONObject without any trouble. I need to change one or more values then return the object to the client (web browser). No matter what I try to do or how I try to go about changing values Delphi is complaining that they are read only.

{"Oid":"{8D03643A-CAEA-4A21-8563-3E0890E30634}","UserName":"User 1","CertificationNumber":"OSHA-CERT007","LastCompany":"{D014A27E-0003-4A5D-8BD7-E37A772DEEDC}","LastLogon":"2017-06-03 21:49:48"}

I need to change the LastCompany and LastLogon properties.

How do I change values on a TJSONObject?

Thank you,
Brian Wheatley
Francesco Marano

Posts: 59
Registered: 11/18/02
Re: Change a TJSONObject value?
Correct
Click to report abuse...   Click to reply to this thread Reply
  Posted: Jun 1, 2017 8:23 PM   in response to: Brian Wheatley in response to: Brian Wheatley
Hello,

It is possible to remove the old value and add a new one, something like this:

const
  cJSONText = '{"Oid":"{8D03643A-CAEA-4A21-8563-3E0890E30634}","UserName":"User 1","CertificationNumber":"OSHA-CERT007","LastCompany":"{D014A27E-0003-4A5D-8BD7-E37A772DEEDC}","LastLogon":"2017-06-03 21:49:48"}';
 
procedure Test();
var
  LJSONValue : TJSONValue;
  LJSONPair : TJSONPair;
begin
  LJSONValue := TJSONObject.ParseJSONValue( cJSONText );
  if (LJSONValue <> nil) and (LJSONValue is TJSONObject) then
  begin
    LJSONPair := TJSONObject(LJSONValue).RemovePair( 'LastCompany' );
    LJSONPair.Free;
 
    TJSONObject(LJSONValue).AddPair( 'LastCompany', TJSONString.Create( '123' ) );
 
    ShowMessage( LJSONValue.ToJSON );
 
  end;
  LJSONValue.Free;
end;


Please note it has a drawback as it changes the fields order.
A better way is to create a shadow model, change the model and recreate the json text.

Regards, Francesco
Legend
Helpful Answer (5 pts)
Correct Answer (10 pts)

Server Response from: ETNAJIVE02