All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.keayuan.util.OptionalJSON Maven / Gradle / Ivy

The newest version!
package cn.keayuan.util;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.keayuan.util.function.BiConsumer;

/**
 * Created by keayuan on 2021/9/26.
 *
 * @author keayuan
 */
public class OptionalJSON {
    private static final String TAG = "OptionalJSON";
    private static final OptionalJSON EMPTY = new OptionalJSON(null);
    private final JSONObject value;

    private OptionalJSON(JSONObject obj) {
        value = obj;
    }

    public static OptionalJSON of(String content) {
        return content == null ? EMPTY : of(parse(content));
    }

    public static OptionalJSON of(JSONObject obj) {
        return obj == null ? EMPTY : new OptionalJSON(obj);
    }

    private static JSONObject parse(String content) {
        if (content != null) {
            try {
                return new JSONObject(content);
            } catch (JSONException e) {
                Platform.logger().e(TAG, "parse error", e);
            }
        }
        return null;
    }

    public OptionalJSON optObject(String key) {
        return of(value == null ? null : value.optJSONObject(key));
    }

    public OptionalJSONArray optArray(String key) {
        return OptionalJSONArray.of(value == null ? null : value.optJSONArray(key));
    }

    public int optInt(String key) {
        return optInt(key, 0);
    }

    public int optInt(String key, int def) {
        if (value == null) return def;
        return value.optInt(key, def);
    }

    public boolean optBoolean(String key) {
        return optBoolean(key, false);
    }

    public boolean optBoolean(String key, boolean def) {
        if (value == null) return def;
        return value.optBoolean(key, def);
    }

    public long optLong(String key) {
        return optLong(key, 0);
    }

    public long optLong(String key, long def) {
        if (value == null) return def;
        return value.optLong(key, def);
    }

    public double optDouble(String key) {
        return optDouble(key, 0);
    }

    public double optDouble(String key, double def) {
        if (value == null) return def;
        return value.optDouble(key, def);
    }

    public String optString(String key) {
        return optString(key, "");
    }

    public String optString(String key, String def) {
        if (value == null) return def;
        return value.optString(key, def);
    }

    public void forEach(BiConsumer consumer) {
        if (value == null || consumer == null) return;
        Iterator keys = value.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            consumer.accept(key, value.opt(key));
        }
    }

    public JSONObject get() {
        return value;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy