Geba
Geba

Reputation: 1372

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);
    }
}

Upvotes: 1

Views: 2794

Answers (2)

Geba
Geba

Reputation: 1372

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);
}

Upvotes: 0

Jason Glez
Jason Glez

Reputation: 1512

With Jackson, I put some methods:

public static Object convertJsonRequestToObject(HttpServletRequest pRequest, Class<?> pObject) throws JsonParseException, JsonMappingException, IOException {
    return new ObjectMapper().readValue(IOUtils.toString(pRequest.getInputStream(), StandardCharsets.UTF_8), pObject);
}

public static Map<String,Object> parseJsonToMap(String json) throws JsonParseException, JsonMappingException, IOException{
    return   new ObjectMapper().readValue(json, HashMap.class);
}

public static Map<String,Object> parseObjectToMap(Object object){
    return  (Map<String, Object>) new ObjectMapper().convertValue(object, Map.class);
}

//inverse
public static Object parseMapToObject(Map<?, ?> pMap, Class<?> pClass){
    return new ObjectMapper().convertValue(pMap, pClass);
}

Upvotes: 1

Related Questions