Serializing an array of arrays in java using Jackson

孤人 提交于 2021-01-29 12:50:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!