|
| 1 | +package com.zetcode; |
| 2 | + |
| 3 | +import com.google.gson.Gson; |
| 4 | +import java.io.FileNotFoundException; |
| 5 | +import java.io.IOException; |
| 6 | +import java.io.Writer; |
| 7 | +import java.nio.charset.StandardCharsets; |
| 8 | +import java.nio.file.Files; |
| 9 | +import java.nio.file.Path; |
| 10 | +import java.nio.file.Paths; |
| 11 | +import java.util.ArrayList; |
| 12 | +import java.util.List; |
| 13 | + |
| 14 | +class Car { |
| 15 | + |
| 16 | + private final String name; |
| 17 | + private final String model; |
| 18 | + private final int price; |
| 19 | + private final String[] colours; |
| 20 | + |
| 21 | + public Car(String name, String model, int price, String[] colours) { |
| 22 | + this.name = name; |
| 23 | + this.model = model; |
| 24 | + this.price = price; |
| 25 | + this.colours = colours; |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +public class GsonDataBindApiWrite { |
| 30 | + |
| 31 | + public static void main(String[] args) throws FileNotFoundException, IOException { |
| 32 | + |
| 33 | + List<Car> cars = new ArrayList<>(); |
| 34 | + cars.add(new Car("Audi", "2012", 22000, new String[]{"gray", "red", "white"})); |
| 35 | + cars.add(new Car("Skoda", "2016", 14000, new String[]{"black", "gray", "white"})); |
| 36 | + cars.add(new Car("Volvo", "2010", 19500, new String[]{"black", "silver", "beige"})); |
| 37 | + |
| 38 | + String fileName = "src/main/resources/cars.json"; |
| 39 | + Path path = Paths.get(fileName); |
| 40 | + |
| 41 | + try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { |
| 42 | + |
| 43 | + Gson gson = new Gson(); |
| 44 | + gson.toJson(cars, writer); |
| 45 | + } |
| 46 | + |
| 47 | + System.out.println("Cars written to file"); |
| 48 | + } |
| 49 | +} |
0 commit comments