1 /* 2 * Copyright (C) 2022 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 package com.android.quicksearchbox 17 18 import android.util.Log 19 import java.util.ArrayList 20 import org.json.JSONException 21 import org.json.JSONObject 22 23 /** SuggestionExtras taking values from a [JSONObject]. */ 24 class JsonBackedSuggestionExtras : SuggestionExtras { 25 private val mExtras: JSONObject 26 override val extraColumnNames: Collection<String> 27 28 constructor(json: String?) { 29 mExtras = JSONObject(json!!) 30 extraColumnNames = ArrayList<String>(mExtras.length()) 31 val it: Iterator<String> = mExtras.keys() 32 while (it.hasNext()) { 33 extraColumnNames.add(it.next()) 34 } 35 } 36 37 constructor(extras: SuggestionExtras) { 38 mExtras = JSONObject() 39 extraColumnNames = extras.extraColumnNames 40 for (column in extras.extraColumnNames) { 41 val value = extras.getExtra(column) 42 mExtras.put(column, value ?: JSONObject.NULL) 43 } 44 } 45 getExtranull46 override fun getExtra(columnName: String?): String? { 47 return try { 48 if (mExtras.isNull(columnName)) { 49 null 50 } else { 51 mExtras.getString(columnName!!) 52 } 53 } catch (e: JSONException) { 54 Log.w(TAG, "Could not extract JSON extra", e) 55 null 56 } 57 } 58 59 @Override toStringnull60 override fun toString(): String { 61 return mExtras.toString() 62 } 63 toJsonStringnull64 override fun toJsonString(): String? { 65 return toString() 66 } 67 68 companion object { 69 private const val TAG = "QSB.JsonBackedSuggestionExtras" 70 } 71 } 72