JSON format in LocalDate field

0

Personal I have the following record being returned by a query using SpringData :

page = grupoService.findByNomeStartingWithOrderByNomeAsc(2, pageable);

If I run the following code:

System.out.println(page.getContent().get(0));

It prints:

Grupo{id=2, dtOperacao='2016-08-26'}

But when I convert to JSON (to be sent to frontend ):

return new ResponseEntity<String>(new Gson().toJson(scSelect), headers, HttpStatus.OK);

It even converts the date to:

{"id": 1, "dtOperacao":{"year":2016,"month":8,"day":26}}

It should however return like this:

dtOperacao='2016-08-26'

Does anyone know how to solve this? Remember that I need to continue using Gson .

    
asked by anonymous 26.08.2016 / 19:44

2 answers

0

I think it's the Serializer. As I'm not sure of the Date Class you're using, if it's a Date, you can use it as follows:

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

EDIT: LocalDate ... sorry

use a serializer

JsonSerializer<Date> localDateSerializer = new JsonSerializer<Date>() {
  @Override
  public JsonElement serialize(LocalDate date, Type typeOfSrc, JsonSerializationContext contex) {
    return return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
  }
};
Gson gson = new GsonBuilder()
   .registerTypeAdapter(LocalDate.class, localDateSerializer)
   .create();
    
03.09.2016 / 00:55
0

I resolved using this function on the front end:

 function convertLocalDateToServer (date) {
        if (date) {
            return $filter('date')(date, 'yyyy-MM-dd');
        } else {
            return null;
        }
    }

And then I just call her before the post to fix the date:

 method: 'POST',
            transformRequest: function (data) {
                if(data.grupo){                     
                    data.grupo.dtOperacao = DateUtils.convertLocalDateToServer(
                            //This convertion is necessary cause the component scselect returns an object date
                            new Date(data.grupo.dtOperacao.year, data.grupo.dtOperacao.month, data.grupo.dtOperacao.day)
                    );                      
                };
                return angular.toJson(data);
    
03.09.2016 / 13:15