How do you customize the java JSON serialization done by Google Cloud Endpoints?

144 Views Asked by At

Below is the relevant method. One of the properties is of LocalDate (Joda).

@ApiMethod(
    name = "taxforms.get",
    path = "tax-forms",
    httpMethod = ApiMethod.HttpMethod.GET
)
public TaxDataList retrieveTaxDataList(
    HttpServletRequest httpServletRequest
) {

    TaxDataList taxDataList = new TaxDataList( );
    TaxData taxData = SampleTax.sampleTaxData( "Tax1098" );
    taxDataList.addFormsItem( taxData );

    return taxDataList;

}

If I do my own serialization, my code includes this:

 ObjectMapper objectMapper = new ObjectMapper( );

 // Special handling for dates
 objectMapper.registerModule( new JodaModule( ) );
 objectMapper.disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS );

 objectMapper.writeValue( sw, data );

 json = sw.toString( );

How can I customize the way the framework does the serialization?

1

There are 1 best solutions below

0
On

This is a close sample code to what you want and which uses transforms java LocalDate and Instant classes into strings and numbers:

package com.company.example;
 
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.Transformer;
 
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
 
@Api(
  name="myApi",
  version="v1",
  transformers={
    MyApi.MyInstantTransformer.class,
    MyApi.MyLocalDateTransformer.class,
  }
)
public class MyApi {
 
  @ApiMethod(name="getStuff")
  public MyStuff getStuff() {
    return new MyStuff();
  }
 
  public static class MyStuff {
    private final LocalDate date;
    private final Instant instant;
    MyStuff() {
      date = LocalDate.now();
      instant = Instant.now();
    }
    public LocalDate getDate() { return date; }
    public Instant getInstant() { return instant; }
  }
 
  public static class MyInstantTransformer implements Transformer<Instant, Long> {
    public Instant transformFrom(Long input) {
      return Instant.ofEpochMilli(input);
    }
    public Long transformTo(Instant input) {
      return input.toEpochMilli();
    }
  }
 
  public static class MyLocalDateTransformer implements Transformer<LocalDate, String> {
    public LocalDate transformFrom(String input) {
      return LocalDate.parse(input, DateTimeFormatter.ISO_LOCAL_DATE);
    }
    public String transformTo(LocalDate input) {
      return input.format(DateTimeFormatter.ISO_LOCAL_DATE);
    }
  }
 
}