This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:
public void writeListToJsonArray() throws IOException {
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, list);
final byte[] data = out.toByteArray();
System.out.println(new String(data));
}
I can't find toByteArray() as @atrioom said, so I use StringWriter, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
writeValueAsString writes it as a JSON-formatted string. For instance if I have a class Coordinate that looks like:
class Coordinate {
private int x;
private int y;
// plus constructor and methods
}
then om.writeValueAsString(new Coordinate(1, 2)) will produce something like
{ "x":1,"y":2 }
instead of whatever the toString method produces.
So, when your client is expecting a JSON-formatted string, use ObjectMapper.writeValueAsString.
comment : is request to return in server.
headers : type of comment json or xml ,html,Image ,multipart ... etc.
see this example :
RestTemplate restTemplate = new RestTemplate();
ObjectMapper mapper = new ObjectMapper();
String requestJson = null;
try {
requestJson = mapper.writeValueAsString(Yourrequest);HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<Object>(requestJson, headers);
LOGGER.info("send request to url {} ", getUrl());
YourTypeOfResponse response = restTemplate.postForObject(URL_LOCAL,
entity, YourTypeOfResponse.class);
} catch (JsonGenerationException e) {
LOGGER.error("JsonGenerationException occurred ", e);
} catch (JsonMappingException e) {
LOGGER.error("JsonMappingException occurred ", e);
} catch (IOException e) {
LOGGER.error("IOException occurred ", e);
}