Files
WS-05-exceptions-and-file-h…/src/main/java/org/FileExamples/ParsingJson/ParsingJsonExample01.java
T

38 lines
1.0 KiB
Java

package org.FileExamples.ParsingJson;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class ParsingJsonExample01 {
static void main() {
try {
Path path = Path.of("data.json");
String texts = new String(Files.readAllBytes(path));
JsonObject rootObject = JsonParser.parseString(texts).getAsJsonObject();
JsonArray genresArray = rootObject.getAsJsonArray("genres");
Gson gson = new Gson();
Type type = new TypeToken<List<Genre>>(){}.getType();
List<Genre> genres = gson.fromJson(genresArray, type);
for(Genre genre: genres)
{
System.out.println(genre.getId() + ". " + genre.getName());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}