ObjectMapper readValue

后端 未结 3 738
猫巷女王i
猫巷女王i 2021-01-22 12:37

I load a ressource file json with the text format

{
    \"sources\": [{
            \"prop1\": \"1\",
            \"prop2\": \"2\"

        },
        {
                 


        
3条回答
  •  庸人自扰
    2021-01-22 12:38

    First thing: Your JSON is invalid. There is a comma after the second object in the sources array. This has to be deleted.

    Second: I think you didn't choose the right type for your result. What your JSON represents is a map which maps from string to an array of objects. So the type should be something like Map (Since you didn't provide the name of your class, I called it Props.

    With these considerations you can construct a MapType by using ObjectMappers getTypeFactory() method and deserialize the value using the constructed type like shown below.

    ObjectMapper mapper = new ObjectMapper();
    TypeFactory typeFactory = mapper.getTypeFactory();
    MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Props[].class);
    Map map = mapper.readValue(s, mapType);
    

提交回复
热议问题