• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.tradefed.util;
18 
19 import com.android.tradefed.log.LogUtil.CLog;
20 import org.json.JSONArray;
21 import org.json.JSONObject;
22 import org.json.JSONException;
23 import java.util.Iterator;
24 
25 /**
26  * A helper class for JSON related operations
27  */
28 public class JsonUtil {
29     /**
30      * Deep merge two JSONObjects.
31      * This method merge source JSONObject fields into the target JSONObject without overwriting.
32      * JSONArray will not be deep merged.
33      *
34      * @param target the target json object to merge
35      * @param source the source json object to read
36      * @throws JSONException
37      */
deepMergeJsonObjects(JSONObject target, JSONObject source)38     public static void deepMergeJsonObjects(JSONObject target, JSONObject source)
39             throws JSONException {
40         Iterator<String> iter = source.keys();
41         while (iter.hasNext()) {
42             String key = iter.next();
43             Object source_value = source.get(key);
44             Object target_value = null;
45             try {
46                 target_value = target.get(key);
47             } catch (JSONException e) {
48                 CLog.d("Merging Json key '%s' into target object.", key);
49                 target.put(key, source_value);
50                 continue;
51             }
52 
53             if (JSONObject.class.isInstance(target_value)
54                     && JSONObject.class.isInstance(source_value)) {
55                 deepMergeJsonObjects((JSONObject) target_value, (JSONObject) source_value);
56             }
57         }
58     }
59 }