Type checking / drop optimization for json building

I am working on a project where we use javax.jsonto process our requests / responses. The implementation we use is org.glassfish.json. What bothers me is that it does not support add / write Object. So I created methods where I have to check every type that this implementation supports. Something like that:

private static void addTypeSafeValue(JsonObjectBuilder jsonBuilder, String key, Object value) {
        if (value instanceof String) {
            jsonBuilder.add(key, value.toString());
        } else if (value instanceof Integer) {
            jsonBuilder.add(key, (int) value);
        } else if (value instanceof Boolean) {
            jsonBuilder.add(key, (boolean) value);
        } else if (value instanceof Long) {
            jsonBuilder.add(key, (long) value);
        } else if (value instanceof Double) {
            jsonBuilder.add(key, (double) value);
        } else if (value instanceof Uri) {
            jsonBuilder.add(key, ((Uri) value).toString());
        } else if (value instanceof Map) {
            jsonBuilder.add(key, convertToJsonObject((Map<String, ?>) value));
        } else if (value instanceof Collection) {
            jsonBuilder.add(key, convertToJsonArray((Collection<?>) value));
        } else if (value instanceof JsonObject) {
            jsonBuilder.add(key, (JsonObject) value);
        } else if (value instanceof JsonArray) {
            jsonBuilder.add(key, (JsonArray) value);
        } else {
            throw new IllegalArgumentException("Not implemented for: " + value.getClass());
        }
    }

I am wondering if there is any way to optimize this code. The other part is what I want to pass JsonObjectBuildereither JsonGeneratorfor the consumer to cut back on some duplicate checks / code.

+4
source share
1 answer

TL; DR , .


, , , ( ) , , , , String byte[].

- , , . .

, , / .

, , ( , ) , , .

, - .

:

1: , . value instanceof Number, . , , , , .

2: Map<Class, Consumer<Object>>, , -

map.get(value.getClass()).accept(value);

, . 10 , , .

, JsonObjectBuilder JsonGenerator , /.

, . JsonObjectBuilder JsonGenerator - . , , - . , . , . .

. , Gson Jackson - .

+1

All Articles