javajsoncollectionsdeserializationtreemap

json (which contains few objects) to TreeMap on java


Could somebody provide code that deserializes json to TreeMap?
I have to use Gson library
This is json:

{
    "сars": [
        {
            "brand": "audi",
            "color": "black"
        },
        {
            "brand": "bmw",
            "color": "white"
        }
    ]
}

This is code that does not work:

public class ReadGarageTest {
    public static void main(String[] args) throws IOException {
        readGarage();
    }

    public static void readGarage() throws IOException {
        Path filePath = Paths.get("example.json");
        String json = Files.readString(filePath);

        Gson gson = new Gson();
        Type type = new TypeToken<TreeMap<String, Car>>(){}.getType();

        TreeMap<String, Car> garage = gson.fromJson(json, type);
        System.out.print(garage);
    }
}

Solution

  • The mistake in the code - attempt to deserialize cars: [] like it is cars: {}

    Gson type has to be new TypeToken<TreeMap<String, List<Car>>>() {}.getType();
    In the question it is new TypeToken<TreeMap<String, Car>>() {}.getType();

    So working code is following

    public static void readGarage() throws IOException {
        Path filePath = Paths.get("example.json");
        String json = Files.readString(filePath);
    
        Gson gson = new Gson();
        Type type = new TypeToken<TreeMap<String, List<Car>>>() {}.getType();
    
        Map<String, List<Car>> garage = gson.fromJson(json, type);
        System.out.print(garage);
    }