简体   繁体   English

日期格式从 Android (java) 到 Spring Boot

[英]Date format from Android (java) to Spring Boot

I'm working with Android Studio (java) to make the front part of my application, and I work with Spring Boot to the back part.我正在使用 Android Studio (java) 制作我的应用程序的前面部分,我使用 Spring Boot 到后面的部分。

The SQL database uses TimeStamp. SQL 数据库使用 TimeStamp。

So my problem is that when I send an object from front (Android) to back (Spring) throws an error:所以我的问题是,当我从前面(Android)向后面(Spring)发送 object 时会抛出一个错误:

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type java.util.Date from String "Feb 18, 2021 2:47:40 AM": not a valid representation (error: Failed to parse Date value 'Feb 18, 2021 2:47:40 AM': Cannot parse date "Feb 18, 2021 2:47:40 AM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"));已解决 [org.springframework.http.converter.HttpMessageNotReadableException: JSON 解析错误:无法从字符串“2021 年 2 月 18 日 2:47:40 AM”中反序列化java.util.Date类型的值:不是有效表示(错误:无法解析日期值“2021 年 2 月 18 日 2:47:40 AM”:无法解析日期“2021 年 2 月 18 日 2:47:40 AM”:不兼容任何标准 forms(“yyyy-MM-dd'T'HH :mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.util.Date from String "Feb 18, 2021 2:47:40 AM": not a valid representation (error: Failed to parse Date value 'Feb 18, 2021 2:47:40 AM': Cannot parse date "Feb 18, 2021 2:47:40 AM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")) at [Source: (PushbackInputStream);嵌套异常是 com.fasterxml.jackson.databind.exc.InvalidFormatException:无法从字符串“2021 年 2 月 18 日 2:47:40 AM”中反序列化类型java.util.Date的值:不是有效表示(错误:无法解析日期值“2021 年 2 月 18 日 2:47:40 AM”:无法解析日期“2021 年 2 月 18 日 2:47:40 AM”:与任何标准 forms(“yyyy-MM-dd'T'HH: mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")) 在[来源:(PushbackInputStream); line: 1, column: 123] (through reference chain: com.prueba.dataproviders.model.Solicitud["fecha"])]行:1,列:123](通过参考链:com.prueba.dataproviders.model.Solicitud["fecha"])]

So I guess the problem its from Android sending information to Spring, but I don't know how to handle it...所以我猜问题是从Android发送信息到Spring,但我不知道如何处理...

MORE INFORMATION: This is an example when I send information from Spring to Android:更多信息:这是我将信息从 Spring 发送到 Android 的示例:

{
    "id": 23,
    "fecha": "2021-02-18T02:47:40.000+00:00",
    "estadoSolicitud": 1
}

I keep the attribute "fecha" which its a date in a Date variable.我将属性“fecha”保留在 Date 变量中,它是一个日期。 But when I send the same object to back it sends:但是当我发送相同的 object 返回时,它发送:

{"estadoSolicitud":0,"fecha":"Feb 18, 2021 2:47:40 AM","id":23}

Thank you in advance <3提前谢谢你 <3

CODE: At Spring Solicitud class:代码:Spring请求 class:

@Entity
@Table(name = "solicitud")
public class Solicitud implements Serializable{

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   @GenericGenerator(name = "increment", strategy = "increment")
   @Column(name = "id")
   private int id;

   @Column(name = "fecha", insertable = false)
   private Date fecha;

   @Column(name="estadoSolicitud")
   private int estadoSolicitud; // "0 Pendiente, 1 Realizada 2 Rechazada

At Spring the the post method that receives the <Solicitud> object:Spring接收<Solicitud> object 的 post 方法:

@RequestMapping(value = "/solicitudes/gestionarSolicitud/{estadoSol}", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<Object> setSolicitud(@RequestBody Solicitud solicitud, @PathVariable(value="estadoSol") int estadoSol ){
        
    Optional<Solicitud> optionalSolicitud = solicitudService.gestionarSolicitud(solicitud, estadoSol);
    if (optionalSolicitud.isPresent()) {
            return new ResponseEntity<Object>(optionalSolicitud.get(), HttpStatus.OK);}

    } else {
        return new ResponseEntity<Object>(null , HttpStatus.OK);
    }   
}

At Android (front part) Solicitud Model: Android (前半部分)征求Model:

public class Solicitud  implements Serializable {

private int id;
private Date fecha;
private int estadoSolicitud; // 0 pendiente 1 Aceptada 2 Rechazada
//getters && setters...

} }

At Android the request method that's request the post method to back:Android请求 post 方法返回的请求方法:

public interface SolicitudService {

@POST("/solicitudes/gestionarSolicitud/{estadoSol}")
Call<Solicitud> gestionarSolitud( @Body Solicitud solicitud,     @Path("estadoSol") int estadoSol);
}

At Android the function that uses the request method:在Android function使用请求方法:

        private void gestionarSolicitud(@NotNull Solicitud solicitud, int estadoSol) {
        SolicitudService solicitudService = ApiClient.getClient().create(SolicitudService.class);
        Call<Solicitud> call = solicitudService.gestionarSolitud(solicitud, estadoSol);

        call.enqueue(new Callback<Solicitud>() {

            @Override
            public void onResponse(Call<Solicitud> call, Response<Solicitud> response) {
                Solicitud solActualizada = response.body();

                if (solActualizada != null && solActualizada.getEstadoSol() == estadoSol) {
                    if (estadoSol == 1)
                        Toast.makeText(context, "Usuario registrado correctamente", Toast.LENGTH_LONG).show();
                    else if (estadoSol == 2)
                        Toast.makeText(context, "Solicitud rechazada", Toast.LENGTH_LONG).show();

                    notifyDataSetChanged();
                } else {
                    Toast.makeText(context, "Ups! Ha ocurrido un error", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<Solicitud> call, Throwable t) {
                Toast.makeText(context, "Ups! Ha ocurrido un error del servidor.", Toast.LENGTH_LONG).show();
            }
        });


    }

I think you have to try Joda Time library as a common middleware for your date fields.我认为您必须尝试将Joda Time 库作为日期字段的通用中间件。

You haven't shown any actual code, so a definitive answer isn't possible, but you need to make sure that whatever you are using to serialize your java objects to Json on the Android side properly serializes Dates to ISO-8601 format.您没有显示任何实际代码,因此不可能给出明确的答案,但您需要确保无论您使用什么将 java 对象序列化为 Android 端的 Json 正确地将日期序列化为 ISO-8601 格式。

Most mainstream Json serializers, eg Gson, will do that by default.大多数主流的 Json 序列化程序,例如 Gson,默认情况下都会这样做。

The exception is saying that the value you are sending from client side(android) is having different data type, what you are fetching in back-end (Spring).异常是说您从客户端(android)发送的值具有不同的数据类型,与您在后端(Spring)中获取的数据类型不同。

At both end the datatype must be same.两端的数据类型必须相同。

Please try this请试试这个

Spring Code: You can mention the date format with JsonFormat annotation Spring 代码:你可以用JsonFormat注解提到日期格式

String DATE_FORMAT_MM_DD_YYYY = "MM/dd/yyyy"字符串 DATE_FORMAT_MM_DD_YYYY = "MM/dd/yyyy"

@JsonFormat(pattern = DATE_FORMAT_MM_DD_YYYY)
private Date fetching_date;

For Android Code: Get the date and you can change the date formats using below code You can define the date formats like this:对于 Android 代码:获取日期,您可以使用以下代码更改日期格式您可以这样定义日期格式:

const val DATE_FORMAT_yyyy_MM_dd_HH_mm_ss_a = "yyyy-MM-dd HH:mm:ss a"
const val DATE_FORMAT_MMM_dd_yyyy = "MMM dd, yyyy"
const val DATE_FORMAT_MMM_dd_yyyy_HH_MM_AA = "MMM dd, yyyy hh:mm aa"
const val DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd"

//Convertion of one date format to another
        fun convertDateFormat(oldFormat: String, newFormat: String, dateString: String): String {
            var sdf = SimpleDateFormat(oldFormat)
            try {
                val date = sdf.parse(dateString)
                sdf = SimpleDateFormat(newFormat, getLocalForDateFormat())
                return sdf.format(date)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return ""
        }

Send the date from android to back-end in request.请求中将android中的日期发送到后端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM