Не получается спарсить дату из JSON

Рейтинг: 0Ответов: 1Опубликовано: 10.05.2023

Всех приветствую! Делаю практику и на последнем этапе стокнулся с проблемой - необходимо из API по запросу получить данные о товарах. API сделано с помощью Swagger на C#. Во время получения данных программа выдает ошибку:

Caused by: java.text.ParseException: Failed to parse date ["2023-06-10T00:00:00']: No time zone indicator

На просторах интернета нашел класс, который должен был помочь:

    public class DateDeserializer implements JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
        String date = element.getAsString();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("GMT"));

        try {
            return format.parse(date);
        } catch (ParseException exp) {
            System.err.println(exp.getMessage());
            return null;
        }
    }
}

Указал его в GsonBuilder:

public static  Retrofit buildRequest() {
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new DateDeserializer())
            .setLenient()
            .create();
    HttpLoggingInterceptor logger = new HttpLoggingInterceptor();
    logger.setLevel(HttpLoggingInterceptor.Level.BODY);
    retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(getUnsafeOkHttpClient().addInterceptor(logger).build())
            .build();
    return retrofit;
}

Однако, это мне не помогло. Код отправки запроса API:

Call<JsonObject> getPositions = apiInterface.getPositions();
    getPositions.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            if(response.isSuccessful()){
                Gson gson = new Gson();
                Type type = new TypeToken<List<Position>>(){}.getType();
                List<Position> positions = gson.fromJson(response.body().get("data"), type);
                for(Position pos : positions){
                    Log.i("Position Details", "ID "+ pos.idPosition + " NAME " + pos.positionName);
                }
            }
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Toast.makeText(DataActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

Возвращаемый JSON:

{"pageNumber":1,"pageSize":10,"data":[{"idPosition":1,"positionName":"Торт птичье молоко","positionQuantity":1,"positionSlife":"2023-06-10T00:00:00","categoryId":1,"photoUrl":"a","isExists":true,"dealerId":1,"positionPrice":400},{"idPosition":2,"positionName":"Печенье дамские пальчики","positionQuantity":1,"positionSlife":"2023-06-10T00:00:00","categoryId":1,"photoUrl":"a","isExists":true,"dealerId":1,"positionPrice":200}],"suceeded":true,"errors":null,"message":null}

Прошу у Вас помощи! Спасибо.

Ответы

▲ 0Принят

Всем спасибо за помощь, разобрался в вопросе. Получилось очень криво и костыльно, но я просто сменил тип данных в БД на varchar, а тип данных в модели на String.