问题
At a certain point in my code, I have parse a JSON document, represented as a string, to a JsonNode
, because I don't know yet the actual target pojo class type.
Now, some time later, I know the Class
instance of the pojo and I want to convert this JsonNode
to an actual pojo of that class (which is annotated with the proper @JsonProperty
annotations). Can this be done? If so, how?
I am working with Jackson 2.10.x.
回答1:
In this case you can use two methods:
- treeToValue
- convertValue
See below example:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.StringJoiner;
public class JsonNodeConvertApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonFile);
System.out.println(mapper.treeToValue(node, Message.class));
System.out.println(mapper.convertValue(node, Message.class));
}
}
class Message {
private int id;
private String body;
// getters, setters, toString
}
Above code for JSON
payload like below:
{
"id": 1,
"body": "message body"
}
prints:
Message[id=1, body='message body']
Message[id=1, body='message body']
来源:https://stackoverflow.com/questions/60991716/how-to-convert-a-jsonnode-instance-to-an-actual-pojo