Jackson deserialization convertValue vs readValue
deserialization, jackson, java, json-deserialization, serialization
Solution
I will try to explain the difference, with the problem I faced. I used both in a complex conversion I needed to use.
My request was of the format as below.
"{Key=a1, type=ABC}"
I wanted to convert it to some class's (A1) instance.
class A1 {
private String key;
private String type;
}
As is clear, the keys are not strings (i.e. not enclosed in double quotes)
With mapper.readValue
I will get error as below:
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('k' (code 115)): was expecting double-quote to start field name
With mapper.convertValue
I will get an instance of A1 as I required.
Problem
I have a org.json.JSONArray that contains JSONObjects and I am trying to map those to a POJO. I know the type of the POJO I want to map to. I have 2 options and I m trying to figure out which is better in performance. Option 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... } ``` Option 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... } ``` For sake of argument, lets assume the length of the JSONArray is 100. From what I have looked so far from the source code, option 1 seems better since the Deserialization context and the Deserializer is created only once, while in case of option 2, it will be done for each call. Thoughts? Thanks!