package org.rx.core.internal; import com.google.gson.*; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import org.rx.beans.JsonObject; import org.rx.core.Reflects; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import static org.rx.core.Contract.tryAs; public class GsonWrapper { public static JsonObject wrap(com.google.gson.JsonObject obj) { return (JsonObject) Enhancer.create(JsonObject.class, new MethodInterceptor() { Gson gson = new Gson(); @Override public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { switch (method.getName()) { case "deepCopy": return wrap(obj.deepCopy()); case "getJsonObject": { String property = (String) args[0]; return wrap(obj.getAsJsonObject(property)); } case "add": { String property = (String) args[0]; Object value = args[1]; if (!tryAs(value, String.class, p -> obj.addProperty(property, p)) && !tryAs(value, Number.class, p -> obj.addProperty(property, p)) && !tryAs(value, Boolean.class, p -> obj.addProperty(property, p))) { obj.add(property, gson.toJsonTree(value)); } return null; } case "remove": String property = (String) args[0]; obj.remove(property); return null; } String fg = "get"; if (method.getName().startsWith("is")) { String property = (String) args[0]; JsonElement element = obj.get(property); return Reflects.invokeMethod(element.getClass(), element, method.getName()); } else if (method.getName().startsWith(fg)) { String property = (String) args[0]; JsonElement element = obj.get(property); return Reflects.invokeMethod(element.getClass(), element, "getAs" + method.getName().substring(fg.length())); } return methodProxy.invoke(obj, args); } }); } }
package org.rx.beans; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import java.math.BigDecimal; import java.math.BigInteger; public interface JsonObject { JsonObject deepCopy(); int size(); boolean has(String property); void add(String property, Object value); void remove(String property); boolean isJsonArray(String property); boolean isJsonObject(String property); boolean isJsonPrimitive(String property); boolean isJsonNull(String property); JsonObject getJsonObject(String property); JsonArray getJsonArray(String property); JsonPrimitive getJsonPrimitive(String property); boolean getBoolean(String property); Number getNumber(String property); String getString(String property); double getDouble(String property); float getFloat(String property); long getLong(String property); int getInt(String property); byte getByte(String property); BigDecimal getBigDecimal(String property); BigInteger getBigInteger(String property); short getShort(String property); }