0

I'm trying to find a generic way to serialize value objects that make use of @JsonValue to a plain string. In particular, I need to suppress the double quotes that Jackson creates. Example:

class Scratch
{
   public static class ValueType
   {
      @JsonValue
      private final String value;

      public ValueType( String value )
      {
         this.value = value;
      }
   }

   public static void main( String[] args ) throws IOException
   {
      ObjectMapper objectMapper = new ObjectMapper();
      ValueType valueType = new ValueType( "1234" );
      String plainValue = objectMapper.writeValueAsString( valueType );
      System.out.println( plainValue ); // prints '"1234"', should print '1234'
   }
}

Instead of "1234", I want the variable plainValue to hold the plain value only, i.e. 1234. Of course I could just strip the double quotes after the string was created, but I was hoping there could be a simple way to directly serialize the object to the required output?

Note that modifying ValueType is not an option, so for example I cannot add @JsonRawValue.

Hein Blöd
  • 1,553
  • 1
  • 18
  • 25
  • You mean you want to serialise `value` as an `int`? – Sweeper Jun 26 '23 at 07:13
  • No, it should still be a `String`. – Hein Blöd Jun 26 '23 at 07:14
  • 1
    Well, `1234` without the quotes is not a JSON string. It's a number. – Sweeper Jun 26 '23 at 07:15
  • I'm aware of the fact that what I'm aiming for would not be valid JSON anymore. I was just hoping that there could be an approach similar to the ones given for example [here](https://stackoverflow.com/questions/28646572/faster-xml-jackson-remove-double-quotes), which work directly on the node tree. Using `1234` as an example was probably a bad idea, `ABC` could have made the intent more clear. – Hein Blöd Jun 27 '23 at 10:05
  • Just to give an idea where my requirement comes from: I've been using such value types inside other Java Beans that are (de-)serialized with Jackson. In this context, creating valid JSON is mandatory, so the double quotes for a field value have to be present. But now I wanted to use the same value types (hence no modification to the existing ones should be made) as `@RequestParam` method parameters for Feign client interfaces. And in this context, the double quotes get in the way because they become part of the URL (e.g. `GET /third-party-service/elements?value="ABC"`). – Hein Blöd Jun 27 '23 at 10:10
  • @HeinBlöd You cannot expect a JSON library to generate invalid JSON. If it could, that would be a bug. – Jorn Jun 27 '23 at 12:36

1 Answers1

0

What you are proposing isn't valid JSON. Strings are always quoted. If you want an int value in your JSON, you have to make it an int in the JSON object. Or, perhaps, you can get away with a custom serializer for ValueType, which does the conversion. But you'd be working against the system, which is never a good idea.

Jorn
  • 20,612
  • 18
  • 79
  • 126