cn.keayuan.util.OptionalJSONArray Maven / Gradle / Ivy
The newest version!
package cn.keayuan.util;
import org.json.JSONArray;
import org.json.JSONException;
import cn.keayuan.util.function.Consumer;
/**
* Created by keayuan on 2021/9/26.
*
* @author keayuan
*/
public class OptionalJSONArray {
private static final String TAG = "OptionalJSONArray";
private static final OptionalJSONArray EMPTY = new OptionalJSONArray(null);
private final JSONArray value;
private OptionalJSONArray(JSONArray arr) {
value = arr;
}
public static OptionalJSONArray of(JSONArray arr) {
return arr == null ? EMPTY : new OptionalJSONArray(arr);
}
public static OptionalJSONArray of(String content) {
return of(parse(content));
}
private static JSONArray parse(String content) {
if (content != null) {
try {
return new JSONArray(content);
} catch (JSONException e) {
Platform.logger().e(TAG, "parse error", e);
}
}
return null;
}
public int optInt(int index) {
return optInt(index, 0);
}
public boolean optBoolean(int index) {
return optBoolean(index, false);
}
public long optLong(int index) {
return optLong(index, 0);
}
public String optString(int index) {
return optString(index, "");
}
public int optInt(int index, int def) {
if (value == null) return def;
return value.optInt(index, def);
}
public boolean optBoolean(int index, boolean def) {
if (value == null) return def;
return value.optBoolean(index, def);
}
public long optLong(int index, long def) {
if (value == null) return def;
return value.optLong(index, def);
}
public double optDouble(int index) {
return optDouble(index, 0);
}
public double optDouble(int index, double def) {
if (value == null) return def;
return value.optDouble(index, def);
}
public String optString(int index, String def) {
if (value == null) return def;
return value.optString(index, def);
}
public OptionalJSON optObject(int index) {
return OptionalJSON.of(value == null ? null : value.optJSONObject(index));
}
public OptionalJSONArray optArray(int index) {
return of(value == null ? null : value.optJSONArray(index));
}
@SuppressWarnings("unchecked")
public void forEach(Consumer consumer) {
if (value == null || consumer == null) return;
int len = value.length();
for (int i = 0; i < len; i++) {
consumer.accept((T) value.opt(i));
}
}
public JSONArray get() {
return value;
}
}