ObjectMapper readValue

后端 未结 3 694
猫巷女王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:44

    In your case, I would write a custom JsonDeserializer. Haven't really tested the code, but I think the idea is clear:

        final MyClassDeserializer myClassDeserializer = new MyClassDeserializer();
        final SimpleModule deserializerModule = new SimpleModule();
        deserializerModule.addDeserializer(MyClass.class, myClassDeserializer);
    
        final ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(deserializerModule);
    

    And the code for JsonDeserializer:

        public class MyClassDeserializer extends JsonDeserializer {
    
        @Override
        public MyClass deserialize(final JsonParser jsonParser, final DeserializationContext context)
                throws IOException {
            final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
            final JsonNode sourcesNode = node.get("sources");
            if(node.isArray()) {
                final ArrayNode arrayNode = (ArrayNode) node;
                final Iterable nodes = arrayNode::elements;
                final Set set = StreamSupport.stream(nodes.spliterator(), false)
                        .map(mapper)
                        .collect(Collectors.toSet());
                ...
            }
    
            ...
        }
    

提交回复
热议问题