How to get the underlying String from a JsonParser (Jackson Json)

后端 未结 5 2181
囚心锁ツ
囚心锁ツ 2021-02-18 15:23

Looking through the documentation and source code I don\'t see a clear way to do this. Curious if I\'m missing something.

Say I receive an InputStream from a server resp

5条回答
  •  眼角桃花
    2021-02-18 15:50

    I had a situation where I was using a custom deserializer, but I wanted the default deserializer to do most of the work, and then using the SAME json do some additional custom work. However, after the default deserializer does its work, the JsonParser object current location was beyond the json text I needed. So I had the same problem as you: how to get access to the underlying json string.

    You can use JsonParser.getCurrentLocation.getSourceRef() to get access to the underlying json source. Use JsonParser.getCurrentLocation().getCharOffset() to find the current location in the json source.

    Here's the solution I used:

    public class WalkStepDeserializer extends StdDeserializer implements
        ResolvableDeserializer {
    
        // constructor, logger, and ResolvableDeserializer methods not shown
    
        @Override
        public MyObj deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
                JsonProcessingException {
            MyObj myObj = null;
    
            JsonLocation startLocation = jp.getCurrentLocation();
            long charOffsetStart = startLocation.getCharOffset();
    
            try {
                myObj = (MyObj) defaultDeserializer.deserialize(jp, ctxt);
            } catch (UnrecognizedPropertyException e) {
                logger.info(e.getMessage());
            }
    
            JsonLocation endLocation = jp.getCurrentLocation();
            long charOffsetEnd = endLocation.getCharOffset();
            String jsonSubString = endLocation.getSourceRef().toString().substring((int)charOffsetStart - 1, (int)charOffsetEnd);
            logger.info(strWalkStep);
    
            // Special logic - use JsonLocation.getSourceRef() to get and use the entire Json
            // string for further processing
    
            return myObj;
        }
    }
    

    And info about using a default deserializer in a custom deserializer is at How do I call the default deserializer from a custom deserializer in Jackson

提交回复
热议问题