I have JSON that looks like this:
{
"values": [
[
123456,
789.0
],
[
123457,
null
]
]
}
"Scheme": each value is an array of exactly two things, the first of which is long, and the second is double (or zero). I would like to parse this into a Java object (just a POJO).
I tried Jackson, but he has a known bug that prevents zeros from working in arrays: https://github.com/FasterXML/jackson-databind/issues/403
I also tried Gson, but apparently it can't handle the idea of โโconverting arrays to Java objects (not Java arrays):
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 3 column 6
Here's the full test class, demonstrating the inoperability of both Jackson and Gson for this simple task:
import java.util.List;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.map.ObjectMapper;
import com.google.gson.Gson;
public class JsonTest {
private static final String TEST_JSON =
"{\n" +
" \"values\": [\n" +
" [\n" +
" 123456,\n" +
" 789.0\n" +
" ],\n" +
" [\n" +
" 123457,\n" +
" null\n" +
" ]\n" +
" ]\n" +
"}\n";
public static class MyPojo1 {
public List<TimestampAndValue> values;
public static class TimestampAndValue {
public long timestamp;
public Double value;
@JsonCreator
public TimestampAndValue(List<Number> nums) {
if(nums == null || nums.size() < 2) {
throw new IllegalArgumentException(String.format("Expected at least two numbers (timestamp & value), instead got: %s", nums));
}
this.timestamp = nums.get(0).longValue();
this.value = nums.get(1).doubleValue();
}
}
}
public static class MyPojo2 {
public List<TimestampAndValue> values;
public static class TimestampAndValue {
public long timestamp;
public Double value;
}
}
public static void main(String[] args) {
try {
System.out.println(new ObjectMapper().readValue(TEST_JSON, MyPojo1.class));
} catch(Throwable t) {
t.printStackTrace();
}
try {
System.out.println(new Gson().fromJson(TEST_JSON, MyPojo2.class));
} catch(Throwable t) {
t.printStackTrace();
}
}
}
: JSON Java? , org.json , .