Home > other >  Console print an array of objects with Jackson
Console print an array of objects with Jackson

Time:02-18

I have a method that exports every POJO person and create an array into a JSON:

Node temp = testa;
ObjectMapper mapper = new ObjectMapper();
FileWriter fileWriter = new FileWriter(Paths.get("jPerson.json").toFile(), true);
SequenceWriter seqWriter = mapper.writer().writeValuesAsArray(fileWriter);  

while (temp != null) {
                seqWriter.write(temp.getPersona());
                temp = temp.getSuccessivo();
        }
seqWriter.close();

I want to create a method that read every object of the array and print it on the screen. This is the prototype, but it prints the hashcode (Person@6a1aab78, etc.):

ObjectMapper mapper = new ObjectMapper();
try {
        Persona[] pJson;
        pJson = mapper.readValue(Paths.get("jPersona.json").toFile(), Persona[].class);
        System.out.println(ReflectionToStringBuilder.toString(pJson));
} catch (IOException e) {
        e.printStackTrace();
}

CodePudding user response:

If you want to print your POJO Persona as JSON, you can use Jackson's ObjectMapper to serialize to a JsonNode and use JsonNode#toString():

final Persona persona = ...;
final JsonNode json = objectMapper.readValue(persona, JsonNode.class);

System.out.println(json);

If you want to print multiple Persona objects, you can iterate:

for(final Persona persona : personas) {
  final JsonNode json = objectMapper.readValue(persona, JsonNode.class);

  System.out.println(json);
}

or, even better, serialize once and iterate:

final Persona[] personas = ...;
final JsonNode jsonArray = objectMapper.valueToTree(personas);

// Check may not be necessary.
if(json.isArray()) {
  // JsonNode implements Iterable.
  for(final JsonNode jsonNode : jsonArray) {
    System.out.println(jsonNode);
  }
}

CodePudding user response:

ReflectionToStringBuilder.toString(Object) doesn't create a "deep" toString method. In your case you could just call Arrays.toString(pJson) and it would have the same result.

Easiest solution is to just override toString in Persona.

public class Persona {
    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }
}

System.out.println(Arrays.toString(pJson));

Or you use a Stream to join all the values in the pJson array to one String.

System.out.println('['   Arrays.stream(pJson)
    .map(ReflectionToStringBuilder::toString)
    .collect(Collectors.joining(", ")) ']');
  • Related