Maven dependency -
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
|
If you are beginner don't worry learn how to Create new Maven project - In 2 minutes
Convert java Object to JSON string and PRETTY PRINT using com.google.gson.Gson in java
package com.ankit.json;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class CreateJsonUsingGoogleJson {
public static void main(String[] args) {
List<String> addesss = new ArrayList<>();
addesss.add("Paris");
addesss.add("London");
Employee employee = new Employee(11, "ankit", addesss, new Date());
Gson googleGson = new GsonBuilder().setPrettyPrinting().create();
String json = googleGson.toJson(employee); // Convert java object to JSON
// string
System.out.println("json = "+json); // Display
// Now - convert java object to JSON string and write to file
try {
FileWriter fileWriter = new FileWriter("c:/Ankit/myJson.json");
googleGson.toJson(employee, fileWriter); //write to file
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//output
/*
json = {
"empId": 11,
"name": "ankit",
"address": [
"Paris",
"London"
],
"birthDate": "Sep 2, 2018 1:57:04 PM"
}
*/
|
Employee class
package com.ankit.json;
import java.util.Date;
import java.util.List;
public class Employee {
//Fields
private int empId;
private String name;
private List<String> address;
private Date birthDate;
public Employee() {
super();
}
public Employee(int empId, String name, List<String> address, Date birthDate) {
super();
this.empId = empId;
this.name = name;
this.address = address;
this.birthDate=birthDate;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", name=" + name + ", address=" + address + ", birthDate=" + birthDate + "]";
}
//Setter and getters
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAddress() {
return address;
}
public void setAddress(List<String> address) {
this.address = address;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
}
|
Related links >
1. Jackson JSON -
We can use Jackson api for for processing JSON in java.
Jackson JSON examples
2. Java provides API (JSR 353) for Processing JSON (JSR 353).
It provides -
- Object Model API
- Streaming API
Java API for JSON processing examples >