Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Json Array to POJO using Jackson

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?

like image 285
Mayank Aggarwal Avatar asked Mar 05 '23 07:03

Mayank Aggarwal


1 Answers

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));
like image 59
Michał Ziober Avatar answered Mar 16 '23 11:03

Michał Ziober