Contains(Key: String): Boolean;
Key. Name of the element used as a key.
The Contains property returns whether there is an element with the specified name.
Available values:
True. The element with the specified name is contained in child elements of the current object.
False. The element with the specified name is not contained in child elements of the current object.
Executing the example requires the JSON file: D:\Work\Json\testfile.json.
Sub UserProc;
Var
Doc: IJsonDocument;
NewJSON: IJsonObjectBuilder;
JSON: IJsonObject;
Element: Boolean;
Name: String;
Begin
// Load JSON structure from the specified file
Doc := New JsonDocument.Create;
Doc.ReadFromFile("D:\Work\Json\testfile.json");
JSON := Doc.RootElement.AsObject;
// Check if the structure contains element named Value
Name := "Value";
Element := JSON.Contains(Name);
If Element Then
Debug.WriteLine("Element is contained in JSON structure");
// Add the Value element with the 100 value if it is absent in the structure
Else
NewJSON := New JsonObjectBuilder.Create;
AddExistElement(JSON, NewJSON);
NewJSON.AddInteger(Name, 100);
Doc := New JsonDocument.Create;
Doc.RootElement := NewJSON.Build;
// Save changes in file
Doc.WriteToFile("D:\Work\Json\testfile.json");
End If;
End Sub UserProc;
Sub AddExistElement(OldJson: IJsonObject; Var NewJson: IJsonObjectBuilder);
Var
i, c: Integer;
Element: IJsonElement;
Begin
c := OldJson.Count;
For i := 0 To c - 1 Do
Element := OldJson.ItemByIndex(i);
Select Case Element.GetType
Case JsonElementType.Boolean: NewJson.AddBoolean(OldJson.Property_(i), Element.AsBoolean);
Case JsonElementType.Double: NewJson.AddDouble(OldJson.Property_(i), Element.AsDouble);
Case JsonElementType.Integer: NewJson.AddInteger(OldJson.Property_(i), Element.AsInteger);
Case JsonElementType.NullValue: NewJson.AddNull(OldJson.Property_(i));
Case JsonElementType.String: NewJson.AddString(OldJson.Property_(i), Element.AsString);
End Select;
End For;
End Sub AddExistElement;
After executing the example, a new element named Value is added to the JSON structure of the testfile.json file if the structure does not contain an element with this name. If an element named Value is contained in the JSON structure, the console displays the corresponding message.
See also: