我有一个关于如何使用Jackson流API将以下文件反序列化为泛型类型变量的问题。
{ “key1”: {“value”:{…} },
“key2”: {“value”:{…} },
“key3”: {“value”:{…}}
}
我有一些代码使用以下命令对整个文件进行反序列化:
Map<K, ValueClass<V>> map = mapper.readValue(new File(fileName), someTypeReferForMapFunc ());
then store to a HashMap using put (omit here)
其中mapper是ObjectMapper。
文件很大。为了减少内存,我使用Jackson streaming API更改了代码如下:
private HashMap<K, ValueClass<V>> loadFileUsingStreamAPI(String fileName){
JsonFactory f = new MappingJsonFactory();
JsonParser jp = f.createJsonParser(new File(fileName));
JsonToken current;
HashMap<K, ValueClass<V>> kvmap = new HashMap(...);
current = jp.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String key = jp.getCurrentName(); (1)
current = jp.nextToken();
if (current == JsonToken.START_OBJECT) {
ValueClass val = mapper.readValue (jp, ValueClass.class);
Kvmap.put(key, val); //(2)
}
else {skip to next object...}
}
return Kvmap;
}
但是,编译在第(2)行失败,因为键应该是K而不是String。我试图将第(1)行更改为:
K key = (K)jp.readValueAs(String.class);
仍然失败。有谁知道如何读取K键作为K键,以便我可以将K键放入Kvmap?
谢谢,