Android REST POST失去日期值

fal*_*ojr 5 java rest android gson android-annotations

我有一个Android应用程序(Spring Android + Android Annotations + Gson),它使用来自Web应用程序(Jersey + Spring + Hibernate/JPA)的REST服务.问题是我的java.util.Date属性没有序列化:

活动(Android应用程序):

...
@Click(R.id.buttonLogin)
void onLoginClick() {
    Student student = new Student();
    student.setDateRegistration(new Date()); //Property where the problem occurs
    student.setFirstName("Venilton");
    student.setGender(Gender.M);

    doSomethingInBackground(student);
}

@Background
void doSomethingInBackground(Student student) {
    this.restClient.insert(student);
}
...
Run Code Online (Sandbox Code Playgroud)

休息客户端(Android应用程序):

@Rest(rootUrl = "http://MY_IP:8080/restful-app", 
    converters = { GsonHttpMessageConverter.class })
public interface StudentRESTfulClient {

    @Post("/student/insert")
    Student insert(Student student);
}
Run Code Online (Sandbox Code Playgroud)

Rest Server(Web App):

@Component
@Path("/student")
public class StudentRESTfulServer {

    @Autowired
    private StudentService studentServiceJpa;

    @POST 
    @Path("/insert")
    public Student insert(Student student) {
        //student.getDateRegistration() is null! It's a problem!

        Student studentResponse = null;
        try {
                this.studentServiceJpa.insert(student);
                studentResponse = student;
        } catch (Exception exception) { }

        return studentResponse;
    }
}
Run Code Online (Sandbox Code Playgroud)

Android应用程序为REST服务执行POST Student对象,但当Student对象到达StudentRESTfulServer时,DateRegistration属性会丢失其值.

你可以帮帮我吗?

Dam*_*zak 3

显然 Gson 不知道如何正确序列化你的日期(有点奇怪,它没有将任何内容放入日志中,或者是吗?)

简单的解决方案是设置您要使用的 Gson 日期格式。为此,您需要创建自定义转换器并使用它而不是GsonHttpMessageConverter

CustomHttpMessageConverter.java

CustomHttpMessageConverter extends GsonHttpMessageConverter {
    protected static final String DATE_FORMAT = "yyyy-MM-dd";

    protected static Gson buildGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();

        gsonBuilder.setDateFormat(DATE_FORMAT);

        return gsonBuilder.create();
    }

    public CustomHttpMessageConverter()  {
        super(buildGson());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的REST 客户端(Android 应用程序)中

@Rest(rootUrl = "http://MY_IP:8080/restful-app", 
converters = { CustomHttpMessageConverter.class })
Run Code Online (Sandbox Code Playgroud)

这应该可以正常工作。

如果仍然无法正常工作

然后你可以在方法内部添加 Gson 所需的任何设置buildGson,例如,如果你需要一些,你可以注册自定义序列化器:

    gsonBuilder.registerTypeAdapter(Date.class, new GsonDateDeSerializer());
Run Code Online (Sandbox Code Playgroud)

但随后您需要在类中实现JsonDeserializerJsonSerializer接口GsonDateDeSerializer

对于自定义序列化/反序列化,您可以查看我的其他答案:GSON Serialize boolean to 0 or 1