1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "rect.h"
17
18 #include "ability_base_log_wrapper.h"
19 #include "nlohmann/json.hpp"
20
21 namespace OHOS {
22 namespace AbilityBase {
23 constexpr const char* VIEW_DATA_RECT_LEFT = "left";
24 constexpr const char* VIEW_DATA_RECT_TOP = "top";
25 constexpr const char* VIEW_DATA_RECT_WIDTH = "width";
26 constexpr const char* VIEW_DATA_RECT_HEIGHT = "height";
27
FromJsonString(const std::string & jsonStr)28 void Rect::FromJsonString(const std::string& jsonStr)
29 {
30 nlohmann::json jsonObject = nlohmann::json::parse(jsonStr, nullptr, false);
31 if (jsonObject.is_discarded()) {
32 ABILITYBASE_LOGE("json parse failed");
33 return;
34 }
35 if (jsonObject.contains(VIEW_DATA_RECT_LEFT) && jsonObject[VIEW_DATA_RECT_LEFT].is_number_float()) {
36 left = jsonObject.at(VIEW_DATA_RECT_LEFT).get<float>();
37 }
38 if (jsonObject.contains(VIEW_DATA_RECT_TOP) && jsonObject[VIEW_DATA_RECT_TOP].is_number_float()) {
39 top = jsonObject.at(VIEW_DATA_RECT_TOP).get<float>();
40 }
41 if (jsonObject.contains(VIEW_DATA_RECT_WIDTH) && jsonObject[VIEW_DATA_RECT_WIDTH].is_number_float()) {
42 width = jsonObject.at(VIEW_DATA_RECT_WIDTH).get<float>();
43 }
44 if (jsonObject.contains(VIEW_DATA_RECT_HEIGHT) && jsonObject[VIEW_DATA_RECT_HEIGHT].is_number_float()) {
45 height = jsonObject.at(VIEW_DATA_RECT_HEIGHT).get<float>();
46 }
47 }
48
ToJsonString() const49 std::string Rect::ToJsonString() const
50 {
51 nlohmann::json jsonObject {
52 {VIEW_DATA_RECT_LEFT, left},
53 {VIEW_DATA_RECT_TOP, top},
54 {VIEW_DATA_RECT_WIDTH, width},
55 {VIEW_DATA_RECT_HEIGHT, height}
56 };
57 return jsonObject.dump();
58 }
59 } // namespace AbilityBase
60 } // namespace OHOS