Java JsonFactory-class And Method Code Example
Here's an example of how to use the JsonFactory class from the Apache Commons IO library to create a JSON object from a Java object and write it to a file:
import org.apache.commons.io.FileUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
// Create a Java object to be converted to JSON
Person person = new Person("John", "Doe", 30);
// Create a JSON factory
JsonFactory jsonFactory = new JsonFactory();
// Create a JSON generator
JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(new File("person.json"), JsonEncoding.UTF8);
// Write the Java object to the JSON generator
jsonGenerator.writeObject(person);
// Close the JSON generator
jsonGenerator.close();
}
}
Here, Person is a class that represents a person.
class Person {
private String firstName;
private String lastName;
private int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// getters and setters here
}
This will write a JSON object to a file called "person.json" that looks like this:
{
"firstName": "John",
"lastName": "Doe",
"age": 30
}
You can also use jsonGenerator.writeStartObject() and jsonGenerator.writeEndObject() to create JSON object manually.
You can read the json file using FileUtils.readFileToString(new File("person.json"), "UTF-8")