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

后端 未结 5 2140
囚心锁ツ
囚心锁ツ 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:55

    Building my own Deserialiser in which I wanted to deserialise a specific field as text i.s.o. a proper DTO, this is the solution I came up with.

    I wrote my own JsonToStringDeserializer like this:

    import com.fasterxml.jackson.core.JsonParser;
    import com.fasterxml.jackson.core.TreeNode;
    import com.fasterxml.jackson.databind.DeserializationContext;
    import com.fasterxml.jackson.databind.JsonDeserializer;
    import lombok.NoArgsConstructor;
    import org.apache.commons.lang3.StringEscapeUtils;
    
    import java.io.IOException;
    
    /**
     * Deserialiser to deserialise any Json content to a String.
     */
    @NoArgsConstructor
    public class JsonToStringDeserializer extends JsonDeserializer {
    
    
        /**
         * Deserialise a Json attribute that is a fully fledged Json object, into a {@link String}.
         * @param jsonParser Parsed used for reading JSON content
         * @param context Context that can be used to access information about this deserialization activity.
         * @return The deserialized value as a {@link String}.
         * @throws IOException
         */
        @Override
        public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
    
            final TreeNode node = jsonParser.getCodec().readTree(jsonParser);
    
            final String unescapedString = StringEscapeUtils.unescapeJava(node.toString());
            return unescapedString.substring(1, unescapedString.length()-1);
        }
    }
    

    Annotate the field you want to deserialize like this:

    @JsonDeserialize(using = JsonToStringDeserializer.class)
    

    I initially followed advice that said to use a TreeNode like this:

        final TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
        return treeNode.toString();
    

    But then you get a Json String that contains escape characters.

提交回复
热议问题