杰克逊反序列化convertValue vs readValue

bsa*_*sam 6 java serialization jackson deserialization json-deserialization

我有一个包含JSONObjects的org.json.JSONArray,我正在尝试将它们映射到POJO.我知道我要映射到的POJO的类型.我有2个选项,我试图找出哪个性能更好.

选项1:

ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.reader().withType(MyPojo.class);

for (int i = 0; i < jsonArr.length(); i++) {
    JSONObject obj = jsonArr.getJSONObject(i);
    MyPojo pojo = reader.readValue(obj.toString());

    ... other code dealing with pojo...
}
Run Code Online (Sandbox Code Playgroud)

选项2:

ObjectReader mapper = new ObjectMapper();

for (int i = 0; i < jsonArr.length(); i++) {
    JSONObject obj = jsonArr.getJSONObject(i);
    MyPojo pojo = mapper.convertvalue(obj, MyPojo.class);

    ... other code dealing with pojo...
}
Run Code Online (Sandbox Code Playgroud)

为了论证,我们假设JSONArray的长度为100.

从我迄今为止看到的源代码看,选项1似乎更好,因为反序列化上下文和反序列化器只创建一次,而在选项2的情况下,它将在每次调用时完成.

思考?

谢谢!

Kno*_*ads 5

我将尝试解释其中的差异以及我面临的问题。我在需要使用的复杂转换中使用了两者。

我的请求的格式如下。

"{Key=a1, type=ABC}"
Run Code Online (Sandbox Code Playgroud)

我想将其转换为某个类的 (A1) 实例。

class A1 {
   private String key;
   private String type;
}
Run Code Online (Sandbox Code Playgroud)

很明显,键不是字符串(即没有用双引号括起来)

使用mapper.readValue

我会收到如下错误:

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('k' (code 115)): was expecting double-quote to start field name
Run Code Online (Sandbox Code Playgroud)

使用mapper.convertValue

我将根据需要获得 A1 的实例。