javaserializationjackson

Creating JSON without quotes


A library is using Map to use some extra information. This map eventually is being converted a JSON object and I need to set request information to display for debugging purposes as this:

map.put("request", requestString);

I am considering to use Jackson specifically to create a JSON without quotes and want to set as requestString.

I am building necessary information regarding Request and building a Map including request headers, parameters, method etc.

Jackson is creating perfectly valid JSON with quotes but when I set this generated value inside map, It is displayed ugly because of having escaped quotes.

So Jackson is creating this:

{
   method : "POST",
   path : "/register"
}

When I set this in map, it turns to this:

{
   method : \"POST\",
   path : \"/register\"
}

Consider this as a huge map including all parameters and other information about request.

What I would like to want this:

{
   method : POST,
   path : /register
} 

I know that this is not a valid JSON but I am using this as a String to a Map which is accepting String values.


Solution

  • public class UnQuotesSerializer extends NonTypedScalarSerializerBase<String>
    {
       public UnQuotesSerializer() { super(String.class); }
    
       /**
        * For Strings, both null and Empty String qualify for emptiness.
        */
       @Override
       public boolean isEmpty(String value) {
          return (value == null) || (value.length() == 0);
       }
    
       @Override
       public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
          jgen.writeRawValue(value);
       }
    
       @Override
       public JsonNode getSchema(SerializerProvider provider, Type typeHint) {
          return createSchemaNode("string", true);
       }
    
       @Override
       public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException {
          if (visitor != null) visitor.expectStringFormat(typeHint);
       }
    }
    

    and

    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("UnQuote");
    module.addSerializer(new UnQuotesSerializer());
    
    objectMapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    objectMapper.registerModule(module);
    

    This is generating without quotes strings.