首先,您过度使用了TJSONObject::ParseJSONValue() 方法。您应该只使用它来解析 TStringStream 文本。一旦你拥有了顶级的TJSONObject*(顺便说一句,你需要在使用完毕后释放它),你就不需要继续调用ParseJSONValue() 来访问它的子对象了。您已经在调用 TJSONObject::GetValue() 以将对象作为 TJSONValue* 指针访问,只需 type-cast 根据需要这些指针,例如:
std::unique_ptr<TStringStream> FileContent(new TStringStream);
FileContent->LoadFromFile(TOUCHGFXREADER_Params.ProjectFullPath);
std::unique_ptr<TJSONValue> tgfxFile(TJSONObject::ParseJSONValue(FileContent->DataString));
if (tgfxFile) {
TJSONObject* Object = static_cast<TJSONObject*>(tgfxFile.get());
TJSONObject* Application = static_cast<TJSONObject*>(Object->GetValue(_D("Application")));
TJSONArray* Screens = static_cast<TJSONArray*>(Application->GetValue(_D("Screens")));
for(int i = 0; i < Screens->Count; i++){
TJSONObject *ScreenObj = static_cast<TJSONObject*>(Screens->Item[i]);
// use ScreenObj as needed...
}
}
现在,话虽如此,您可以操作 TJSONArray 来添加新元素(TJSONArray::Add() 和 TJSONArray::AddElement()),并删除元素(TJSONArray::Remove()),但您不能用新值替换元素.您必须删除所需的元素,然后插入一个新元素。
如果您只想更改数组中现有对象的内容,您已经可以访问每个元素的TJSONObject* 指针,因此您可以根据需要操作这些对象,即使用TJSONObject:AddPair()、@ 987654334@等
但是,修改TJSONObject 中的现有值有点棘手。 Delphi 的 JSON 框架并非旨在修改现有值,仅用于读取文档和构建新文档。您可以要求 TJSONObject 给您一个 TJSONValue* 以获得所需的子值,然后将其类型转换为适当的类型(TJSONString*、TJSONNumber* 等)并从其各自的属性中读取(TJSONString::Value、 TJSONNumber::AsInt 等),例如:
bool override = static_cast<TJSONBool*>(ScreenObj->GetValue(_D("OverrideDefaultBufferSize")))->AsBoolean;
但是你不能给它分配一个新的值。
因此,修改 TJSONObject 中的值的唯一方法是:
- 通过
TJSONObject::RemovePair() 删除所需的值,然后使用TJSONObject::AddPair() 插入同名的新值。
ScreenObj->RemovePair(_D("OverrideDefaultBufferSize"));
ScreenObj->AddPair(_D("OverrideDefaultBufferSize"), new TJSONBool(...));
- 向
TJSONObject 询问包含所需值的TJSONPair,然后分配其jsonValue 属性以指向所需类型的新值。一定要释放旧值,否则会泄露。
TJSONPair *pair = ScreenObj->Get(_D("OverrideDefaultBufferSize"));
TJSONValue *old = pair->jsonValue;
pair->jsonValue = new TJSONBool(...);
delete old;