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 21 import org.json.JSONException; 22 import org.json.JSONObject; 23 24 import java.util.Iterator; 25 26 /** 27 * A helper class for JSON related operations 28 */ 29 public class JsonUtil { 30 /** 31 * Deep merge two JSONObjects. 32 * This method merge source JSONObject fields into the target JSONObject without overwriting. 33 * JSONArray will not be deep merged. 34 * 35 * @param target the target json object to merge 36 * @param source the source json object to read 37 * @throws JSONException 38 */ deepMergeJsonObjects(JSONObject target, JSONObject source)39 public static void deepMergeJsonObjects(JSONObject target, JSONObject source) 40 throws JSONException { 41 Iterator<String> iter = source.keys(); 42 while (iter.hasNext()) { 43 String key = iter.next(); 44 Object source_value = source.get(key); 45 Object target_value = null; 46 try { 47 target_value = target.get(key); 48 } catch (JSONException e) { 49 CLog.d("Merging Json key '%s' into target object.", key); 50 target.put(key, source_value); 51 continue; 52 } 53 54 if (JSONObject.class.isInstance(target_value) 55 && JSONObject.class.isInstance(source_value)) { 56 deepMergeJsonObjects((JSONObject) target_value, (JSONObject) source_value); 57 } 58 } 59 } 60 }