in the code import com.google.gson.Gson; import com.google.gson.reflect.TypeToken;…
- User
in the code import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List;
class Hotel{ int id; String name; String description; String city; String phone; List services; int rate; Ratings ratings; }
class Ratings { private int cleaning; private int position; private int services; private int quality;
// Getters e setters omessi per brevità – devono essere inclusi}
public class Server { String HotelsPath ="Hotels.json"; Gson gson = new Gson(); String content; private List hotels;
public Server() throws IOException{ try{ String content = new String(Files.readAllBytes(Paths.get(HotelsPath))); Type hotelListType = new TypeToken<List<Hotel>>(){}.getType(); List<Hotel> hotels = gson.fromJson(content, hotelListType); } catch(IOException e){ throw e; } } public static void main(String[] args){ System.out.println("ciao"); try{ Server server = new Server(); for(Hotel hotel : server.hotels){ System.out.println(hotel.name); } } catch(IOException e){ e.printStackTrace(); } }} i get error at line 50, why??
- Assistant
The error you're encountering is likely due to a
NullPointerExceptionon line 50, which is the following line in yourmainmethod:for(Hotel hotel : server.hotels){This happens because the
hotelsfield in theServerclass is never actually initialized with the list of hotels loaded from the JSON file. You have declared a local variablehotelsinside the constructor of theServerclass instead of assigning the loaded list to the fieldhotels.To fix this, you need to remove the type declaration from the
hotelsassignment inside the constructor of theServerclass so that it initializes the class field rather than creating a new local variable. Here's how the corrected code in the constructor should look:public Server() throws IOException { try { content = new String(Files.readAllBytes(Paths.get(HotelsPath))); Type hotelListType = new TypeToken<List<Hotel>>(){}.getType(); hotels = gson.fromJson(content, hotelListType); // Remove the 'List<Hotel>' type declaration here } catch (IOException e) { throw e; } }