1. Jackson
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.2</version>
</dependency>
</dependencies>
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class JsonReader {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
MyClass object = objectMapper.readValue(new File("data.json"), MyClass.class);
System.out.println(object);
}
}
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class JsonWriter {
public static void main(String[] args) throws IOException {
MyClass object = new MyClass("John", 25);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(new File("data.json"), object);
}
}
2. Gson
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.7</version>
</dependency>
</dependencies>
import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
public class JsonReader {
public static void main(String[] args) throws IOException {
Gson gson = new Gson();
MyClass object = gson.fromJson(new FileReader("data.json"), MyClass.class);
System.out.println(object);
}
}
import com.google.gson.Gson;
import java.io.FileWriter;
import java.io.IOException;
public class JsonWriter {
public static void main(String[] args) throws IOException {
MyClass object = new MyClass("John", 25);
Gson gson = new Gson();
gson.toJson(object, new FileWriter("data.json"));
}
}
3. JSON.simple
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileReader;
import java.io.IOException;
public class JsonReader {
public static void main(String[] args) throws IOException, ParseException {
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(new FileReader("data.json"));
System.out.println(object);
}
}
import org.json.simple.JSONObject;
import java.io.FileWriter;
import java.io.IOException;
public class JsonWriter {
public static void main(String[] args) throws IOException {
JSONObject object = new JSONObject();
object.put("name", "John");
object.put("age", 25);
FileWriter fileWriter = new FileWriter("data.json");
object.writeJSONString(fileWriter);
fileWriter.flush();
fileWriter.close();
}
}