Rewrite ArrayDeserializerin equivalent form, but more expressive
class ArrayDeserializer implements JsonDeserializer<int[]> {
@Override
public int[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonArray jsonArray = json.getAsJsonObject().getAsJsonArray("test");
return context.deserialize(jsonArray, int[].class);
}
}
JsonDeserializationContext#deserializeJavadoc state
. , JsonDeserializer.deserialize(JsonElement, Type,
JsonDeserializationContext). , Gson .
, , , , stackoverflow .
?
( )
deserialize {test:[0,3]} as int[]
take given JSON as an object (OK), extract 'test' as JSON array (OK)
deserialize [0,3] as int[]
take given JSON as an object (FAIL)
, , JSON JSON, ArrayDeserializer JSON.
return gson.fromJson(json.getAsJsonObject().getAsJsonArray("test"), int[].class);
"test" JSON Gson, ArrayDeserializer.
new Gson().fromJson("[0,3]", int[].class);
int[] 0 3. .
.
POJO
class Pojo {
private int[] test;
public int[] getTest() {
return test;
}
public void setTest(int[] test) {
this.test = test;
}
}
Pojo pojo = new Gson().fromJson(json, Pojo.class);
int[] arr = pojo.getTest();
Gson gson = new Gson();
JsonArray jsonArray = gson.toJsonTree(json).getAsJsonObject().get("test").getAsJsonArray();
int[] arr = gson.fromJson(jsonArray, int[].class);