JSON format in Localdate field

Asked

Viewed 715 times

0

Personal have the record sequinte 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));

He 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);

The same converts the date to:

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

But he should return like this:

dtOperacao='2016-08-26'

Does anyone know how to solve this? Remembering that I need to keep using the Gson.

2 answers

0

I believe it is Serializer. As I am not sure of the Date Class you are using, if it is 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();

0

I solved using this function in front-end:

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

And then I only 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.