Java SequenceWriter-class And Method Code Example
The SequenceWriter class from the com.fasterxml.jackson.databind package is used to write a sequence of JSON values, such as an array or a list of objects. This class provides methods for writing JSON values, such as strings, numbers, and objects, to a JSON output stream.
Here is an example of how to use the SequenceWriter class to write a list of Java objects to a JSON array:
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SequenceWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void main(String[] args) throws Exception {
JsonFactory factory = new JsonFactory();
StringWriter writer = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
SequenceWriter seqWriter = mapper.writer().writeValues(factory.createGenerator(writer));
List<MyObject> myObjects = new ArrayList<>();
MyObject obj1 = new MyObject("John", 30);
MyObject obj2 = new MyObject("Jane", 25);
myObjects.add(obj1);
myObjects.add(obj2);
for (MyObject obj : myObjects) {
seqWriter.write(obj);
}
seqWriter.close();
System.out.println(writer.toString());
}
}
class MyObject {
private String name;
private int age;
public MyObject(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
In this example, a JsonFactory is used to create a SequenceWriter instance that writes to a StringWriter. The SequenceWriter writes out a list of MyObject instances as a JSON array. The code loops through the list of MyObject instances, writing each one to the SequenceWriter.
When this code is run, it will output the following JSON string:
[{"name":"John","age":30},{"name":"Jane","age":25}]
This example shows how to write a sequence of JSON values, in this case, a list of MyObject instances, to a JSON output stream. The SequenceWriter class provides a convenient way to write a sequence of JSON values, such as an array or a list of objects, to a JSON output stream.