问题
I'm learning how to use Jackson and I have to serialize an array of ContoCorrente objects
public class ContoCorrente {
private String proprietario;
private ArrayList<MovimentoBancario> movimenti;
//methods...
}
where MovimentoBancario is defined as
public class MovimentoBancario {
private String data;
private String causale;
//methods...
}
I tried with
ArrayList<ContoCorrente> conti= new ArrayList<ContoCorrente>(50);
for(int i=0; i<50; i++){
//fill array
}
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
System.out.println(mapper.writeValueAsString(conti));
} catch (Exception e) {
e.printStackTrace();
}
but the output is
[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]
I don't know what I'm doing wrong, it's the first time I try serialization
回答1:
You can try defining a specific method using Jackson.
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final ObjectReader reader = new ObjectMapper().readerFor(Array.class);
public static String toArray(ArrayList<ContoCorrente> array) throws JsonProcessingException {
return objectMapper.writeValueAsString(array);
}
Then if you want to read just use the reader.
来源:https://stackoverflow.com/questions/64702095/serializing-an-array-of-arrays-in-java-using-jackson