Java tutorial
//package com.java2s; /* Copyright 2014 GhanaianFramework. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import android.os.Bundle; import android.text.TextUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Iterator; public class Main { /** * * @param jsonObject * @return */ @SuppressWarnings("unchecked") public static Bundle parseBundle(JSONObject jsonObject) { Bundle bundle = null; if (jsonObject != null) { bundle = new Bundle(jsonObject.length()); for (Iterator<String> iterator = jsonObject.keys(); iterator.hasNext();) { String key = iterator.next(); Object object = null; try { object = jsonObject.get(key); } catch (JSONException e) { if (isLogEnabled()) { e.printStackTrace(); } } putBundleObject(bundle, key, object); } } return bundle; } /** * if its enabled exceptions will be written into stack trace. * @return */ protected static boolean isLogEnabled() { return false; } /** * * @param bundle * @param key * @param object */ private static void putBundleObject(Bundle bundle, String key, Object object) { if (bundle != null && object != null && !TextUtils.isEmpty(key)) { if (object instanceof String) { bundle.putString(key, (String) object); } else if (object instanceof Boolean) { bundle.putBoolean(key, (Boolean) object); } else if (object instanceof Double) { bundle.putDouble(key, (Double) object); } else if (object instanceof Float) { Float value = (Float) object; bundle.putDouble(key, (double) value); } else if (object instanceof Integer) { bundle.putInt(key, (Integer) object); } else if (object instanceof Long) { bundle.putLong(key, (Long) object); } else if (object instanceof JSONObject) { object = parseBundle((JSONObject) object); bundle.putBundle(key, (Bundle) object); } else if (object instanceof JSONArray) { int elementQuantity = ((JSONArray) object).length(); Bundle subBundle = new Bundle(elementQuantity); for (int i = 0; i < elementQuantity; i++) { Object subObject = getArrayValue((JSONArray) object, i, null); if (subObject != null) { putBundleObject(subBundle, key, subObject); } } } } } /** * * @param array * @param index * @param defaultValue * @return */ public static Object getArrayValue(JSONArray array, int index, Object defaultValue) { Object value = defaultValue; if (array != null) { try { if (!array.isNull(index)) { value = array.get(index); } } catch (Exception e) { if (isLogEnabled()) { e.printStackTrace(); } } } return value; } }