问题
I have a JSON array of the form:
[
[
1232324343,
"A",
"B",
3333,
"E"
],
[
12345424343,
"N",
"M",
3133,
"R"
]
]
I want to map each element of the parent array to a POJO using the Jackson library. I tried this:
ABC abc = new ABC();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(data).get("results");
if (jsonNode.isArray()) {
for (JsonNode node : jsonNode) {
String nodeContent = mapper.writeValueAsString(node);
abc = mapper.readValue(nodeContent,ABC.class);
System.out.println("Data: " + abc.getA());
}
}
where ABC is my POJO class and abc is the object but I get the following exception:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.demo.json.model.ABC
EDIT: My POJO looks like this:
class ABC{
long time;
String a;
String b;
int status;
String c;
}
Can someone suggest a solution for this?
EDIT 2: After consulting a lot of answers on StackOverflow and other forums, I came across one solution. I mapped the returned value of readValue() method into an array of POJO objects.
ABC[] abc = mapper.readValue(nodeContent, ABC[].class);
But now I am getting a separate exception
Can not construct instance of ABC: no long/Long-argument constructor/factory method to deserialize from Number value (1552572583232)
I have tried the following but nothing worked: 1. Forcing Jackson to use ints for long values using
mapper.configure(DeserializationFeature.USE_LONG_FOR_INTS, true);
2. Using wrapper class Long instead of long in the POJO
Can anyone help me with this?
回答1:
You can use ARRAY
shape for this object. You can do that using JsonFormat
annotation:
@JsonFormat(shape = Shape.ARRAY)
class ABC {
And deserialise it:
ABC[] abcs = mapper.readValue(json, ABC[].class);
EDIT after changes in question.
You example code could look like this:
JsonNode jsonNode = mapper.readTree(json);
if (jsonNode.isArray()) {
for (JsonNode node : jsonNode) {
String nodeContent = mapper.writeValueAsString(node);
ABC abc = mapper.readValue(nodeContent, ABC.class);
System.out.println("Data: " + abc.getA());
}
}
We can use convertValue
method and skip serializing process:
JsonNode jsonNode = mapper.readTree(json);
if (jsonNode.isArray()) {
for (JsonNode node : jsonNode) {
ABC abc = mapper.convertValue(node, ABC.class);
System.out.println("Data: " + abc.getA());
}
}
Or even:
JsonNode jsonNode = mapper.readTree(json);
ABC[] abc = mapper.convertValue(jsonNode, ABC[].class);
System.out.println(Arrays.toString(abc));
回答2:
Your json does not map to the pojo that you have defined. For the pojo that you have defined, the json should be of the form below.
{
"time:1232324343,
"a":"A",
"b":"B",
"status":3333,
"c":"E"
}
来源:https://stackoverflow.com/questions/55256971/mapping-json-array-to-pojo-using-jackson