title: Using Jackson to serialize a Guava Optional<Integer> as a string
body: <p>I have a value object with an <code>Optional&lt;Integer&gt;</code> field. <strong>I want it to look like a string when it's serialized</strong>, but the <code>Optional</code> part is getting in the way.</p>
  
  <p>I have the following class:</p>
  
  <pre><code>public class Person {
      private com.google.common.base.Optional&lt;Integer&gt; age;
      public com.google.common.base.Optional&lt;Integer&gt; getAge() {
          return age;
      }
      public void setAge(Integer age) {
          this.age = com.google.common.base.Optional.fromNullable(age);
      }
  }
  </code></pre>
  
  <p>Here is my test:</p>
  
  <pre><code>@Test
  public void testPerson() throws Exception {
      ObjectMapper objectMapper = new ObjectMapper().registerModule(new GuavaModule());
      Person person = new Person();
      person.setAge(1);
      String jsonString = objectMapper.writeValueAsString(person);
      assertEquals(jsonString, "{\"age\":\"1\"}");
  }
  </code></pre>
  
  <p>It's failing with this output:</p>
  
  <blockquote>
    <p>java.lang.AssertionError: expected [{"age":"1"}] but found [{"age":1}]</p>
  </blockquote>
  
  <p>I have tried adding a <code>@JsonSerialize</code> annotation to the property, like this:</p>
  
  <pre><code>@JsonSerialize(using = ToStringSerializer.class)
  private com.google.common.base.Optional&lt;Integer&gt; age;
  </code></pre>
  
  <p>But then the test fails like this:</p>
  
  <blockquote>
    <p>java.lang.AssertionError: expected [{"age":"1"}] but found [{"age":"Optional.of(1)"}]</p>
  </blockquote>
  
  <p>I've been looking around in <code>com.fasterxml.jackson.datatype.guava.ser.GuavaOptionalSerializer</code> but I can't seem to figure out how to use it correctly, if even if it's meant to be used this way.</p>
  
  <p>What can I do to get this test working?</p>
  
  <p>P.S. If it were up to me, I would remove the Optional altogether, but that's not an option.</p>