Felhasználói eszközök

Eszközök a webhelyen


oktatas:programozas:java:java_json:gson

< Java JSON

Java JSON - Gson

Beszerzés

Employee osztály

Legyen egy Employee osztály, amiben egy dolgozó adatait tároljuk:

Employee.java
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.

App.java
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.

App.java
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

App.java
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

App.java
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<Employee> 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

App.java
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<Employee> 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<Employee> 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

database.json
{
    "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.
src/Places.java
public class Places {
    Place[] fishingspots;
}
src/Place.java
public class Place {
    Integer id;
    String name;
    Integer spot;
    String date;
    Integer rods;
    Boolean paid;
}
src/Mainconsole.java
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);
        }
    }
 
}
src/App.java
public class App {
    public static void main(String[] args) throws Exception {
        new Mainconsole();
    }
}

Elnevezett JSON tömb listába

database.json
{
    "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
      },
    ]
}
src/Places.java
public class Places {
    Place[] fishingspots;
}
src/Place.java
public class Place {
    Integer id;
    String name;
    Integer spot;
    String date;
    Integer rods;
    Boolean paid;
}
src/Mainconsole.java
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<Place> 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:

database.json
[
    {
        "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
    }
]
src/Mainconsole.java
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<Place> 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);
        }
    }    
}
Place.java
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;
    }
 
}
src/App.java
public class App {
    public static void main(String[] args) throws Exception {
        new Mainconsole();
    }
}

LocalDate használata

database.json
[
  {
    "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
  }
]
src/App.java
import java.time.LocalDate;
 
public class Place {
        Integer id;
        String name;
        Integer spot;
        LocalDate date;
        Integer rods;
        Boolean paid;
}
src/Mainconsole.java
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<Place> 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<LocalDate>() { 
            @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);
        }
    }    
}
App.java
public class App {
    public static void main(String[] args) throws Exception {
        new Mainconsole();
    }
}

Forrás

oktatas/programozas/java/java_json/gson.txt · Utolsó módosítás: 2024/01/24 13:49 szerkesztette: admin