使用javax.json将JSON字符串转换为Java对象

5

我正在使用com.google.gson.Gson API将一个JSON字符串转换为Java对象:

Gson gson = new Gson();
User u = gson.fromJson(jsonString, User.class);

我想知道在javax.json API中是否有相应的API来执行等价操作。 谢谢!


可以实现,但绝对不是一行代码就能搞定的。你需要使用Java Beans Introspector API来帮助你。这样可以吗? - BalusC
是的,只使用JSON API调用将是可接受的。 - V G
2个回答

9
这是与Gson一样简单的单行代码不可能做到的。javax.json API非常底层,它只返回一个JSON对象结构,需要你自己进一步分解和映射到javabean。
为了实现与Gson#fromJson()几乎相同的效果,这里有一个引导示例的样板代码。支持带参数类型和javabean,全部使用标准Java SE API,javabean通过少量使用java.beans API进行内省。
@SuppressWarnings("unchecked")
public static <T> T fromJson(String json, Class<T> beanClass) {
    JsonValue value = Json.createReader(new StringReader(json)).read();
    return (T) decode(value, beanClass);
}

private static Object decode(JsonValue jsonValue, Type targetType) {
    if (jsonValue.getValueType() == ValueType.NULL) {
        return null;
    }
    else if (jsonValue.getValueType() == ValueType.TRUE || jsonValue.getValueType() == ValueType.FALSE) {
        return decodeBoolean(jsonValue, targetType);
    }
    else if (jsonValue instanceof JsonNumber) {
        return decodeNumber((JsonNumber) jsonValue, targetType);
    }
    else if (jsonValue instanceof JsonString) {
        return decodeString((JsonString) jsonValue, targetType);
    }
    else if (jsonValue instanceof JsonArray) {
        return decodeArray((JsonArray) jsonValue, targetType);
    }
    else if (jsonValue instanceof JsonObject) {
        return decodeObject((JsonObject) jsonValue, targetType);
    }
    else {
        throw new UnsupportedOperationException("Unsupported json value: " + jsonValue);
    }
}

private static Object decodeBoolean(JsonValue jsonValue, Type targetType) {
    if (targetType == boolean.class || targetType == Boolean.class) {
        return Boolean.valueOf(jsonValue.toString());
    }
    else {
        throw new UnsupportedOperationException("Unsupported boolean type: " + targetType);
    }
}

private static Object decodeNumber(JsonNumber jsonNumber, Type targetType) {
    if (targetType == int.class || targetType == Integer.class) {
        return jsonNumber.intValue();
    }
    else if (targetType == long.class || targetType == Long.class) {
        return jsonNumber.longValue();
    }
    else {
        throw new UnsupportedOperationException("Unsupported number type: " + targetType);
    }
}

private static Object decodeString(JsonString jsonString, Type targetType) {
    if (targetType == String.class) {
        return jsonString.getString();
    }
    else if (targetType == Date.class) {
        try {
            return new SimpleDateFormat("MMM dd, yyyy H:mm:ss a", Locale.ENGLISH).parse(jsonString.getString()); // This is default Gson format. Alter if necessary.
        }
        catch (ParseException e) {
            throw new UnsupportedOperationException("Unsupported date format: " + jsonString.getString());
        }
    }
    else {
        throw new UnsupportedOperationException("Unsupported string type: " + targetType);
    }
}

private static Object decodeArray(JsonArray jsonArray, Type targetType) {
    Class<?> targetClass = (Class<?>) ((targetType instanceof ParameterizedType) ? ((ParameterizedType) targetType).getRawType() : targetType);

    if (List.class.isAssignableFrom(targetClass)) {
        Class<?> elementClass = (Class<?>) ((ParameterizedType) targetType).getActualTypeArguments()[0];
        List<Object> list = new ArrayList<>();

        for (JsonValue item : jsonArray) {
            list.add(decode(item, elementClass));
        }

        return list;
    }
    else if (targetClass.isArray()) {
        Class<?> elementClass = targetClass.getComponentType();
        Object array = Array.newInstance(elementClass, jsonArray.size());

        for (int i = 0; i < jsonArray.size(); i++) {
            Array.set(array, i, decode(jsonArray.get(i), elementClass));
        }

        return array;
    }
    else {
        throw new UnsupportedOperationException("Unsupported array type: " + targetClass);
    }
}

private static Object decodeObject(JsonObject object, Type targetType) {
    Class<?> targetClass = (Class<?>) ((targetType instanceof ParameterizedType) ? ((ParameterizedType) targetType).getRawType() : targetType);

    if (Map.class.isAssignableFrom(targetClass)) {
        Class<?> valueClass = (Class<?>) ((ParameterizedType) targetType).getActualTypeArguments()[1];
        Map<String, Object> map = new LinkedHashMap<>();

        for (Entry<String, JsonValue> entry : object.entrySet()) {
            map.put(entry.getKey(), decode(entry.getValue(), valueClass));
        }

        return map;
    }
    else try {
        Object bean = targetClass.newInstance();

        for (PropertyDescriptor property : Introspector.getBeanInfo(targetClass).getPropertyDescriptors()) {
            if (property.getWriteMethod() != null && object.containsKey(property.getName())) {
                property.getWriteMethod().invoke(bean, decode(object.get(property.getName()), property.getWriteMethod().getGenericParameterTypes()[0]));
            }
        }

        return bean;
    }
    catch (Exception e) {
        throw new UnsupportedOperationException("Unsupported object type: " + targetClass, e);
    }
}

使用方法:

User u = YourJsonUtil.fromJson(jsonString, User.class);

如果您在使用decodeXxx()方法之一时遇到UnsupportedOperationException,只需将所需的转换逻辑添加到相关方法中即可。当然,这可以进一步重构以应用策略模式等,使其更加灵活和可扩展,但这样做基本上就是重新发明Gson。


2

没有,不存在其他解析器比GSON更好。

在尝试其他解析器之前,请注意:org.json存在漏洞/实现错误。QuickJson存在漏洞/实现错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接