com.google.gson.JsonSyntaxException when trying to parse Date/Time in json

前端 未结 3 1478
有刺的猬
有刺的猬 2021-01-11 09:17

I\'m using RestTemplete to get json data from a rest api and I\'m using Gson to parse data from json format to Object

Gson gson = new Gson();

restTemplate =         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-11 10:02

    What I've done finally is going to my API project and create a CustomSerializer

    public class CustomDateSerializer extends JsonSerializer {  
    
        @Override
        public void serialize(Date t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = formatter.format(t);
    
            jg.writeString(formattedDate);
        }
    }
    

    that return the format yyyy-MM-dd and I annotated date fields with

    @JsonSerialize(using = CustomDateSerializer.class)
    

    in my Android application I created Gson object as

                Reader reader = new InputStreamReader(content);
    
                GsonBuilder gsonBuilder = new GsonBuilder();
                gsonBuilder.setDateFormat("yyyy-MM-dd");
                Gson gson = gsonBuilder.create();
                appels = Arrays.asList(gson.fromJson(reader, Appel[].class));
                content.close();
    

    and it works for now .. thanks for your help I appreciate it

提交回复
热议问题