断言对象是一个有效的顶级 json 可序列化
Asserting object is a valid top level json serializable
我想确保 o
是可序列化的顶级 JSON 对象,即 []
或 {}
否则会抛出异常。我已经使用 ""
和 null
作为输入尝试了以下代码,但它们没有触发异常。
static void checkIsjsonSerializable(Object o, String message)
throws MissingRequiredValueException {
try{
Gson gson = new Gson();
gson.toJson(o);
} catch (Exception e) {
throw new MissingRequiredValueException(message);
}
}
需要更改什么才能获得我想要的支票?
更新:
评论后很明显我的理解是错误的。我的问题已更改为:
How can I assert only [] and {} are valid in the following function?
正如其他人所提到的,JSON do 的现代定义允许基元(字符串、数字、布尔值、null)作为顶级元素。但是如果你真的需要用 GSON 做这个检查,这里有一个选择:
private static final Gson gson = new Gson();
static void checkIsjsonSerializable(Object o, String message)
throws MissingRequiredValueException {
JsonElement rootElement = gson.toJsonTree(o);
if (!rootElement.isJsonArray() && !rootElement.isJsonObject()) {
throw new MissingRequiredValueException(message);
}
}
我想确保 o
是可序列化的顶级 JSON 对象,即 []
或 {}
否则会抛出异常。我已经使用 ""
和 null
作为输入尝试了以下代码,但它们没有触发异常。
static void checkIsjsonSerializable(Object o, String message)
throws MissingRequiredValueException {
try{
Gson gson = new Gson();
gson.toJson(o);
} catch (Exception e) {
throw new MissingRequiredValueException(message);
}
}
需要更改什么才能获得我想要的支票?
更新: 评论后很明显我的理解是错误的。我的问题已更改为:
How can I assert only [] and {} are valid in the following function?
正如其他人所提到的,JSON do 的现代定义允许基元(字符串、数字、布尔值、null)作为顶级元素。但是如果你真的需要用 GSON 做这个检查,这里有一个选择:
private static final Gson gson = new Gson();
static void checkIsjsonSerializable(Object o, String message)
throws MissingRequiredValueException {
JsonElement rootElement = gson.toJsonTree(o);
if (!rootElement.isJsonArray() && !rootElement.isJsonObject()) {
throw new MissingRequiredValueException(message);
}
}