我有一个这样的JSON:
{
"values": [
[
123456,
789.0
],
[
123457,
null
]
]
}
"schema"是这样的:每个值都是一个包含两个元素的数组,第一个是长整型,第二个是双精度浮点数(或null)。我想将它解析成Java对象(仅为POJO)。
我尝试了Jackson,但它有一个已知的bug,防止数组中的null起作用:https://github.com/FasterXML/jackson-databind/issues/403 我还尝试了Gson,但它显然无法处理将数组转换为Java对象的想法(而不是Java数组):
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 3 column 6
这里有一个完整的测试类,演示了Jackson和Gson在这个简单任务中的无法工作:
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提供的原始材料来构建自己的简单解析器,因为现有的库并不是那么方便。
TEST_JSON
中删除\n
,这将提高可读性并不会影响行为。 - Dmitry Ginzburg