From Clomosy Docs

No edit summary
No edit summary
Line 49: Line 49:
|-
|-
| '''ToJSONString''' || obj.ToJSONString; || Serializes the object into a JSON string format.
| '''ToJSONString''' || obj.ToJSONString; || Serializes the object into a JSON string format.
|-
| '''FromJSONString''' || obj.FromJSONString(jsonStr); || Replaces current data with the content of a JSON string.
|-
|-
| '''Clear''' || obj.Clear; || Removes all key–value pairs from the object.
| '''Clear''' || obj.Clear; || Removes all key–value pairs from the object.
Line 182: Line 180:


Output:
Output:
[[File:TCLJSONObject.png|frameless|600px]]<br>
[[File:TCLJSONObject.png|frameless|600px]]<br>



Revision as of 11:18, 22 October 2025

The TCLJSONObject class represents a JSON object composed of key–value pairs. It provides structured methods to add, remove, clone, merge, and retrieve data. Objects can contain nested objects or arrays, allowing hierarchical and deeply structured JSON representations. TCLJSONObject ensures type safety by operating with TCLJSONValue, preventing data inconsistency during serialization and deserialization.


Information: JSON Object Structure
A JSON object is an unordered collection of name–value pairs, where each name is a string and the value may be a string, number, boolean, array, or another object.
Example: {"name":"Alice","age":25,"active":true}
Feature Use of Definition
TCLJSONObject obj : TCLJSONObject; Creates a variable for JSON object.
Create obj = TCLJSONObject.Create; Initializes a new empty JSON object instance.
CreateFromJSON obj = TCLJSONObject.CreateFromJSON(jsonStr); Creates a JSON object from a JSON string.
AddPair obj.AddPair('name', TCLJSONValue.Str('Alice')); Adds a key–value pair to the object.
SetValue obj.SetValue('age', TCLJSONValue.Int(25)); Updates an existing key’s value or adds it if not present.
RemovePair obj.RemovePair('age'); Removes a key and its corresponding value.
AddObject obj.AddObject('address', ChildObj); Adds a nested JSON object as a child.
AddArray obj.AddArray('scores', Arr); Adds a JSON array under a key.
HasKey obj.HasKey('active'); Checks whether the specified key exists.
GetValue val = obj.GetValue('name'); Retrieves the value of a given key as a TCLJSONValue.
GetValueByPath val = obj.GetValueByPath('user.profile.name'); Retrieves a value using dot notation for nested structures.
Merge obj.Merge(ExtraObj); Merges another object’s pairs into the current object.
Clone copy = obj.Clone; Creates a deep copy of the object, including all nested items.
ToJSONString obj.ToJSONString; Serializes the object into a JSON string format.
Clear obj.Clear; Removes all key–value pairs from the object.
Count obj.Count; Returns the number of key–value pairs within the object.
IsEmpty obj.IsEmpty; Returns True if the object contains no pairs.
SaveToFile TCLJSON.SaveObjectToFile(obj, 'data.json'); Saves the current object to a file.
LoadFromFile obj = TCLJSON.LoadObjectFromFile('data.json'); Loads a JSON object from a file.
IsValidJSON TCLJSON.IsValidJSON(jsonStr); Checks if the string is a valid JSON format.
Important: Nested Object Access
Use GetValueByPath to access deeply nested elements.

Example: user.GetValueByPath('account.details.email') returns the email value from a nested JSON structure.

Important Notes

  • All key names in TCLJSONObject are case-sensitive.
  • Nested paths must use dot notation.
  • When merging objects, existing keys are overwritten by the new object’s values.
  • Use Clone for duplication instead of manual re-construction to preserve data integrity.
  • Always free JSON objects after use to avoid memory leaks.

Example: TCLJSONObject in Use

var
  MyForm: TClForm;
  NameEdt, AgeEdt, CityEdt: TClProEdit;
  ActiveChk: TClCheckBox;
  CreateBtn: TClProButton;
  ResultMemo: TClMemo;

void GenerateJSONObject
var
  Obj, Child, Extra: TCLJSONObject;
  Val: TCLJSONValue;
{
  try
    Obj = TCLJSONObject.Create;
    Child = TCLJSONObject.Create;
    Extra = TCLJSONObject.Create;
    try
      // Key-value pairs
      Obj.AddPair('name', TCLJSONValue.Str(NameEdt.Text));
      Obj.AddPair('age', TCLJSONValue.Int(StrToIntDef(AgeEdt.Text, 0)));
      Obj.AddPair('active', TCLJSONValue.Bool(ActiveChk.IsChecked));

      // Nested object
      Child.AddPair('city', TCLJSONValue.Str(CityEdt.Text));
      Obj.AddObject('address', Child);

      // Additional info (merge)
      Extra.AddPair('status', TCLJSONValue.Str('OK'));
      Obj.Merge(Extra);

      // Retrieve deep value
      Val = Obj.GetValueByPath('address.city');
      ShowMessage('City: ' + Val.AsString);

      // Show JSON output
      ResultMemo.Lines.Text = Obj.ToJSONString;

    except
      ShowMessage('An error occurred while creating JSON: ' + LastExceptionMessage);
    }
  finally
    Obj.Free;
    Child.Free;
    Extra.Free;
  }
}

{
  MyForm = TClForm.Create(Self);

  NameEdt = MyForm.AddNewProEdit(MyForm, 'NameEdt', 'Name');
  NameEdt.Align = alTop;
  NameEdt.Height = 35;
  NameEdt.Margins.Left = 25;
  NameEdt.Margins.Bottom = 25;
  NameEdt.Margins.Right = 25;

  AgeEdt = MyForm.AddNewProEdit(MyForm, 'AgeEdt', 'Age');
  AgeEdt.Align = alTop;
  AgeEdt.Height = 35;
  AgeEdt.Margins.Left = 25;
  AgeEdt.Margins.Bottom = 25;
  AgeEdt.Margins.Right = 25;

  CityEdt = MyForm.AddNewProEdit(MyForm, 'CityEdt', 'City');
  CityEdt.Align = alTop;
  CityEdt.Height = 35;
  CityEdt.Margins.Left = 25;
  CityEdt.Margins.Bottom = 25;
  CityEdt.Margins.Right = 25;

  ActiveChk = MyForm.AddNewCheckBox(MyForm, 'ActiveChk', 'Is Active?');
  ActiveChk.Align = alTop;
  ActiveChk.Margins.Left = 15;
  ActiveChk.Margins.Top = 10;

  ResultMemo = MyForm.AddNewMemo(MyForm, 'ResultMemo', 'JSON Output');
  ResultMemo.Align = alClient;
  ResultMemo.Height = 200;
  ResultMemo.TextSettings.WordWrap = True;

  CreateBtn = MyForm.AddNewProButton(MyForm, 'CreateBtn', 'Generate JSON');
  CreateBtn.Align = alBottom;
  CreateBtn.Margins.Left = 15;
  CreateBtn.Margins.Right = 15;
  CreateBtn.Margins.Bottom = 10;
  CreateBtn.OnClick = 'GenerateJSONObject';

  MyForm.Run;
}

Output:


TCLJSONObject.png


See Also