var I: Integer; CurrentObject: TJSONObject; FieldName: string; Pair: TJSONPair; function CreateJSONValueForVariant(const aValue: Variant): TJSONValue; begin case VarType(aValue) of varInteger: Result := TJSONNumber.Create(Integer(aValue)); // 直接为整数创建TJSONNumber varSingle, varDouble: Result := TJSONNumber.Create(Double(aValue)); // 对于单精度和双精度浮点数,直接传入Value varString: Result := TJSONString.Create(string(aValue)); varBoolean: Result := TJSONBool.Create(aValue); else raise Exception.CreateFmt('Unsupported variant type encountered: %s', [VarToStr(aValue)]); // 更详细的错误信息 end; end; begin CurrentObject := JsonObject; for I := Low(FieldNames) to High(FieldNames) - 1 do begin FieldName := FieldNames[I]; if not CurrentObject.TryGetValue(FieldName, CurrentObject) or not (CurrentObject is TJSONObject) then begin // 如果路径段不存在或不是对象,则创建一个新的对象 CurrentObject.AddPair(FieldName, TJSONObject.Create); CurrentObject := CurrentObject.Values[FieldName] as TJSONObject; end else begin // 继续深入到下一个路径段 CurrentObject := CurrentObject.Values[FieldName] as TJSONObject; end; end; // 到达最后一级路径,设置值 FieldName := FieldNames[High(FieldNames)]; Pair := CurrentObject.Get(FieldName); if Pair = nil then CurrentObject.AddPair(FieldName, CreateJSONValueForVariant(NewValue)) // 自动根据NewValue类型创建JSONValue else Pair.JsonValue := CreateJSONValueForVariant(NewValue); Result := JsonObject; end;
调用: var JsonObject : TJSONObject; JsonObject := TJSONObject.ParseJSONValue('{}') as TJSONObject; JsonObject :=TSQLHelp.UpdateNestedJSONField(JsonObject, ['person', 'age'], Integer(30)); ShowMessage(JsonObject.ToString);
根据path:['person', 'age']检查json,有就更新,没有就创建。是否非常方便!
标签:27,end,unigui,aValue,JsonObject,json,CurrentObject,TJSONObject,FieldName From: https://www.cnblogs.com/usegear/p/18228490