Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - best way writes a java list to a json array

Tags:

java

json

jackson

I want to use jackson to convert a ArrayList to a JsonArray.

Event.java : this is the java bean class with two fields "field1", "field2" mapped as JsonProperty.

My goal is:

Convert

ArrayList<Event> list = new ArrayList<Event>();     list.add(new Event("a1","a2"));     list.add(new Event("b1","b2")); 

To

[ {"field1":"a1", "field":"a2"}, {"field1":"b1", "field":"b2"} ] 

The way I can think of is: writeListToJsonArray():

public void writeListToJsonArray() throws IOException {       ArrayList<Event> list = new ArrayList<Event>();     list.add(new Event("a1","a2"));     list.add(new Event("b1","b2"));      OutputStream out = new ByteArrayOutputStream();      JsonFactory jfactory = new JsonFactory();     JsonGenerator jGenerator = jfactory.createJsonGenerator(out, JsonEncoding.UTF8);     ObjectMapper mapper = new ObjectMapper();     jGenerator.writeStartArray(); // [      for (Event event : list) {         String e = mapper.writeValueAsString(event);         jGenerator.writeRaw(usage);         // here, big hassles to write a comma to separate json objects, when the last object in the list is reached, no comma      }      jGenerator.writeEndArray(); // ]      jGenerator.close();      System.out.println(out.toString()); } 

I am looking for something like:

generator.write(out, list)   

this directly convert the list to json array format and then write it to outputstream "out".

even greedier:

generator.write(out, list1)  generator.write(out, list2) 

this will just convert/add in the list1, list2 into a single json array. then write it to "out"

like image 309
Shengjie Avatar asked Nov 22 '12 14:11

Shengjie


People also ask

How can we convert a list to the JSON array in Java?

We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.

How do I convert a JSON list to Jackson?

We can convert a List to JSON array using the writeValueAsString() method of ObjectMapper class and this method can be used to serialize any Java value as a String.

How does Jackson read JSON array?

Reading JSON from a File Thankfully, Jackson makes this task as easy as the last one, we just provide the File to the readValue() method: final ObjectMapper objectMapper = new ObjectMapper(); List<Language> langList = objectMapper. readValue( new File("langs. json"), new TypeReference<List<Language>>(){}); langList.

How does Jackson convert object to JSON?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.


2 Answers

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)); } 
like image 96
Perception Avatar answered Sep 20 '22 17:09

Perception


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)); 
like image 43
JaskeyLam Avatar answered Sep 20 '22 17:09

JaskeyLam