JSONUtil.java 2.75 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  org.apache.sling.commons.json.JSONArray
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 */
package com.adobe.cq.mobile.dps.impl.utils;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;

public abstract class JSONUtil {
    public static String getSafeString(JSONObject jsonObject, String key) {
        String value = null;
        try {
            value = jsonObject.getString(key);
        }
        catch (JSONException ex) {
            // empty catch block
        }
        return value;
    }

    public static boolean getSafeBoolean(JSONObject jsonObject, String key, boolean defaultIfMissing) {
        boolean value = defaultIfMissing;
        try {
            value = jsonObject.getBoolean(key);
        }
        catch (JSONException ex) {
            // empty catch block
        }
        return value;
    }

    public static int getSafeInt(JSONObject jsonObject, String key) {
        try {
            return jsonObject.getInt(key);
        }
        catch (JSONException ex) {
            throw new RuntimeException("Data missing for:" + key);
        }
    }

    public static JSONObject getSafeJSONObject(JSONObject jsonObject, String key) {
        JSONObject value = null;
        try {
            value = jsonObject.getJSONObject(key);
        }
        catch (JSONException ex) {
            // empty catch block
        }
        return value;
    }

    public static JSONArray getSafeJSONArray(JSONObject jsonObject, String key) {
        JSONArray value = null;
        try {
            value = jsonObject.getJSONArray(key);
        }
        catch (JSONException ex) {
            // empty catch block
        }
        return value;
    }

    public static Object getSafeObject(JSONObject jsonObject, String key) {
        Object value = null;
        try {
            value = jsonObject.get(key);
        }
        catch (JSONException ex) {
            // empty catch block
        }
        return value;
    }

    public static Set<String> getKeys(JSONObject jsonObject) {
        HashSet<String> keysSet = new HashSet<String>();
        Iterator keysIter = jsonObject.keys();
        while (keysIter.hasNext()) {
            keysSet.add((String)keysIter.next());
        }
        return keysSet;
    }

    public static JSONArray appendJSONArrays(JSONArray jsonArray1, JSONArray jsonArray2) throws JSONException {
        for (int i = 0; i < jsonArray2.length(); ++i) {
            jsonArray1.put(jsonArray2.get(i));
        }
        return jsonArray1;
    }
}