[[oktatas:programozás:java:java_json|< Java JSON]]
====== Java JSON - Gson ======
* **Szerző:** Sallai András
* Copyright (c) 2021, Sallai András
* Szerkesztve: 2021-2023
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]]
* Web: https://szit.hu
===== Beszerzés =====
* https://github.com/google/gson (2022)
* https://search.maven.org/artifact/com.google.code.gson/gson/2.8.9/jar (2022)
* Jobb oldalon "Download"
===== Employee osztály =====
Legyen egy Employee osztály, amiben egy dolgozó adatait tároljuk:
public class Employee {
String name;
String city;
double salary;
public Employee(String name, String city, double salary) {
this.name = name;
this.city = city;
this.salary = salary;
}
}
===== Objektumból JSON sztring =====
Adjuk a projektünkhöz a json-x.y.z.jar fájlt.
Készítünk egy egyszerű objektumot az Employee osztályból, majd JSON sztringgé alakítva kiírjuk.
import com.google.gson.Gson;
public class App {
public static void main(String[] args) throws Exception {
Employee emp = new Employee("Csendes Imre", "Szeged", 342);
Gson gson = new Gson();
System.out.println(gson.toJson(emp));
}
}
Kimenet
{"name":"Csendes Imre","city":"Szeged","salary":342.0}
A JSON kimenetet egyetlen sorban látjuk.
===== Szép kimenet =====
Ha olvashatóbb kimenet szereténk látni használjuk a GsonBuilder osztályt.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class App {
public static void main(String[] args) throws Exception {
Employee emp = new Employee("Csendes Imre", "Szeged", 342);
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
Gson gson = builder.create();
String jsonStr = gson.toJson(emp);
System.out.println(jsonStr);
}
}
{
"name": "Csendes Imre",
"city": "Szeged",
"salary": 342.0
}
===== JSON sztringből objektum =====
import com.google.gson.Gson;
public class App {
public static void main(String[] args) throws Exception {
Employee emp = new Employee("Csendes Imre", "Szeged", 342);
Gson gson = new Gson();
String jsonStr = gson.toJson(emp);
Employee empCopy = gson.fromJson(jsonStr, Employee.class);
System.out.println(empCopy.name);
System.out.println(empCopy.city);
System.out.println(empCopy.salary);
}
}
Kimenet:
Csendes Imre
Szeged
342.0
===== ArrayList-ből JSON sztring =====
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class App {
public static void main(String[] args) throws Exception {
Employee emp1 = new Employee("Csendes Imre", "Szeged", 342);
Employee emp2 = new Employee("Gépi Roland", "Szeged", 345);
ArrayList empList = new ArrayList<>();
empList.add(emp1);
empList.add(emp2);
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
Gson gson = builder.create();
String jsonStr = gson.toJson(empList.toArray());
System.out.println(jsonStr);
}
}
Kimenet:
[
{
"name": "Csendes Imre",
"city": "Szeged",
"salary": 342.0
},
{
"name": "Gépi Roland",
"city": "Szeged",
"salary": 345.0
}
]
===== JSON sztringből ArrayList =====
import java.util.ArrayList;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class App {
public static void main(String[] args) throws Exception {
Employee emp1 = new Employee("Csendes Imre", "Szeged", 342);
Employee emp2 = new Employee("Gépi Roland", "Szeged", 345);
ArrayList empList = new ArrayList<>();
empList.add(emp1);
empList.add(emp2);
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
Gson gson = builder.create();
String jsonStr = gson.toJson(empList.toArray());
//Visszalakítás
Employee[] empArray = gson.fromJson(jsonStr, Employee[].class);
ArrayList empListCopy = new ArrayList<>(Arrays.asList(empArray));
System.out.println(empListCopy.get(0).name);
System.out.println(empListCopy.get(1).name);
}
}
Kimenet:
Csendes Imre
Gépi Roland
===== JSON fájl olvasása =====
==== Elnevezett JSON tömb olvasása ====
{
"fishingspots": [
{
"id": 1,
"name": "Bátori Dániel",
"spot": 35,
"date": "2023-04-17",
"rods": 3,
"paid": true
},
{
"id": 2,
"name": "Szeredi Petra",
"spot": 23,
"date": "2023-04-19",
"rods": 3,
"paid": true
},
{
"id": 3,
"name": "Kovács Richárd",
"spot": 20,
"date": "2023-04-19",
"rods": 6,
"paid": false
},
]
}
Az oszátáyok mezőneveik meg kell egyezzenek a JSON fájlban tárolt tulajdonságok neveivel.
public class Places {
Place[] fishingspots;
}
public class Place {
Integer id;
String name;
Integer spot;
String date;
Integer rods;
Boolean paid;
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.Gson;
public class Mainconsole {
public Mainconsole() {
this.readFile();
}
public void readFile() {
try {
tryReadFile();
} catch (FileNotFoundException e) {
System.err.println("Hiba! A fájl nem található!");
}
}
public void tryReadFile()
throws FileNotFoundException {
Gson gson = new Gson();
FileReader fr = new FileReader("database.json");
BufferedReader br = new BufferedReader(fr);
Places placeData = gson.fromJson(br, Places.class);
for(Place place : placeData.fishingspots) {
System.out.println(place.name);
}
}
}
public class App {
public static void main(String[] args) throws Exception {
new Mainconsole();
}
}
==== Elnevezett JSON tömb listába ====
{
"fishingspots": [
{
"id": 1,
"name": "Bátori Dániel",
"spot": 35,
"date": "2023-04-17",
"rods": 3,
"paid": true
},
{
"id": 2,
"name": "Szeredi Petra",
"spot": 23,
"date": "2023-04-19",
"rods": 3,
"paid": true
},
{
"id": 3,
"name": "Kovács Richárd",
"spot": 20,
"date": "2023-04-19",
"rods": 6,
"paid": false
},
]
}
public class Places {
Place[] fishingspots;
}
public class Place {
Integer id;
String name;
Integer spot;
String date;
Integer rods;
Boolean paid;
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Mainconsole {
ArrayList placeList;
public Mainconsole() {
this.placeList = new ArrayList<>();
this.readFile();
}
public void readFile() {
try {
tryReadFile();
} catch (FileNotFoundException e) {
System.err.println("Hiba! A fájl nem található!");
}
}
public void tryReadFile()
throws FileNotFoundException {
Gson gson = new Gson();
FileReader fr = new FileReader("database.json");
BufferedReader br = new BufferedReader(fr);
Places placeData = gson.fromJson(br, Places.class);
for(Place place : placeData.fishingspots) {
placeList.add(place);
}
}
}
===== Leképezés listába =====
A JSON fájlban is eleve lista van, név nélkül:
[
{
"id": 1,
"name": "Bátori Dániel",
"spot": 35,
"date": "2023-04-17",
"rods": 3,
"paid": true
},
{
"id": 2,
"name": "Szeredi Petra",
"spot": 23,
"date": "2023-04-19",
"rods": 3,
"paid": true
},
{
"id": 3,
"name": "Kovács Richárd",
"spot": 20,
"date": "2023-04-19",
"rods": 6,
"paid": false
}
]
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Mainconsole {
ArrayList placeList;
public Mainconsole() {
this.placeList = new ArrayList<>();
this.readFile();
}
public void readFile() {
try {
tryReadFile();
} catch (FileNotFoundException e) {
System.err.println("Hiba! A fájl nem található!");
}
}
public void tryReadFile()
throws FileNotFoundException {
Gson gson = new Gson();
FileReader fr = new FileReader("database.json");
BufferedReader br = new BufferedReader(fr);
Place[] data = gson.fromJson(br, Place[].class);
for(Place place : data) {
placeList.add(place);
System.out.println(place.name);
}
}
}
public class Place {
Integer id;
String name;
Integer spot;
String date;
Integer rods;
Boolean paid;
public Place(Integer id, String name, Integer spot, String date, Integer rods, Boolean paid) {
this.id = id;
this.name = name;
this.spot = spot;
this.date = date;
this.rods = rods;
this.paid = paid;
}
}
public class App {
public static void main(String[] args) throws Exception {
new Mainconsole();
}
}
===== LocalDate használata =====
[
{
"id": 1,
"name": "Bátori Dániel",
"spot": 35,
"date": "2023-04-17",
"rods": 3,
"paid": true
},
{
"id": 2,
"name": "Szeredi Petra",
"spot": 23,
"date": "2023-04-19",
"rods": 3,
"paid": true
},
{
"id": 3,
"name": "Kovács Richárd",
"spot": 20,
"date": "2023-04-19",
"rods": 6,
"paid": false
}
]
import java.time.LocalDate;
public class Place {
Integer id;
String name;
Integer spot;
LocalDate date;
Integer rods;
Boolean paid;
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class Mainconsole {
ArrayList placeList;
public Mainconsole() {
this.placeList = new ArrayList<>();
this.readFile();
}
public void readFile() {
try {
tryReadFile();
} catch (FileNotFoundException e) {
System.err.println("Hiba! A fájl nem található!");
}
}
public void tryReadFile()
throws FileNotFoundException {
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDate.class, new JsonDeserializer() {
@Override
public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return LocalDate.parse(json.getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd")); }
}).create();
FileReader fr = new FileReader("database.json");
BufferedReader br = new BufferedReader(fr);
Place[] data = gson.fromJson(br, Place[].class);
for(Place place : data) {
placeList.add(place);
System.out.println(place.name);
}
}
}
public class App {
public static void main(String[] args) throws Exception {
new Mainconsole();
}
}
===== Forrás =====
* https://www.tutorialspoint.com/gson/gson_quick_guide.htm (2022)