1 /* 2 * Copyright (C) 2010 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 org.json.JSONException; 19 import org.json.JSONObject; 20 21 import android.util.Log; 22 23 import java.util.ArrayList; 24 import java.util.Collection; 25 import java.util.Iterator; 26 27 /** 28 * SuggestionExtras taking values from a {@link JSONObject}. 29 */ 30 public class JsonBackedSuggestionExtras implements SuggestionExtras { 31 private static final String TAG = "QSB.JsonBackedSuggestionExtras"; 32 33 private final JSONObject mExtras; 34 private final Collection<String> mColumns; 35 36 public JsonBackedSuggestionExtras(String json) throws JSONException { 37 mExtras = new JSONObject(json); 38 mColumns = new ArrayList<String>(mExtras.length()); 39 Iterator<String> it = mExtras.keys(); 40 while (it.hasNext()) { 41 mColumns.add(it.next()); 42 } 43 } 44 45 public JsonBackedSuggestionExtras(SuggestionExtras extras) throws JSONException { 46 mExtras = new JSONObject(); 47 mColumns = extras.getExtraColumnNames(); 48 for (String column : extras.getExtraColumnNames()) { 49 String value = extras.getExtra(column); 50 mExtras.put(column, value == null ? JSONObject.NULL : value); 51 } 52 } 53 54 public String getExtra(String columnName) { 55 try { 56 if (mExtras.isNull(columnName)) { 57 return null; 58 } else { 59 return mExtras.getString(columnName); 60 } 61 } catch (JSONException e) { 62 Log.w(TAG, "Could not extract JSON extra", e); 63 return null; 64 } 65 } 66 67 public Collection<String> getExtraColumnNames() { 68 return mColumns; 69 } 70 71 @Override 72 public String toString() { 73 return mExtras.toString(); 74 } 75 76 public String toJsonString() { 77 return toString(); 78 } 79 80 } 81