Reputation: 26882
Is it possible to have fastjson2 deserialize a JSON array into a primitive array of float/ints? Ideally without boxing/unboxing the numbers.
I found that there is a option JSONReader.Feature.UseDoubleForDecimals
which gets me half way there, but I can't figure out how to have it use primitive arrays instead of List<Integer>
etc.
It must use fastjson2 (so using Jackson is not an option).
This code:
void test() {
enum TestEnum {
A, B, C
}
// Prepare data
Map<TestEnum, Object> testData = Map.of(
TestEnum.A, "test",
TestEnum.B, new String[]{"test1", "test2"},
TestEnum.C, new float[]{1.0f, 2.0f, 3.0f}
);
// Serialize
String serialized = JSON.toJSONString(testData);
System.out.println("Serialized: " + serialized);
JSONObject read = JSON.parseObject(serialized, JSONReader.Feature.UseDoubleForDecimals);
for (Map.Entry<String, Object> stringObjectEntry : read.entrySet()) {
System.out.println(stringObjectEntry.getKey() + " " + stringObjectEntry.getValue().getClass() + " " + (stringObjectEntry.getValue() instanceof List));
}
System.out.println(read);
}
Prints:
Serialized: {"A":"test","C":[1.0,2.0,3.0],"B":["test1","test2"]}
A class java.lang.String false
C class com.alibaba.fastjson2.JSONArray true
B class com.alibaba.fastjson2.JSONArray true
{"A":"test","C":[1.0,2.0,3.0],"B":["test1","test2"]}
But I want it to use float[]
for the key TestEnum.C when it's deserialized, not JSONArray
(List
).
Upvotes: 0
Views: 55