草庐IT

java - Android REST POST 丢失日期值

coder 2023-12-14 原文

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

Activity (安卓应用):

...
@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);
}
...

休息客户端(安卓应用):

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

    @Post("/student/insert")
    Student insert(Student student);
}

休息服务器(网络应用程序):

@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;
    }
}

Android 应用程序为 REST 服务执行 POST 学生对象,但当学生对象到达 StudentRESTfulServer 时,DateRegistration 属性失去其值。

你能帮帮我吗?

最佳答案

显然 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());
    }
}

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

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

这应该可以正常工作。

如果还是不行

然后您可以在 buildGson 方法中添加 Gson 所需的任何设置,例如如果需要,您可以注册自定义序列化程序:

    gsonBuilder.registerTypeAdapter(Date.class, new GsonDateDeSerializer());

但是您需要在 GsonDateDeSerializer 类中实现 JsonDeserializerJsonSerializer 接口(interface)。

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

关于java - Android REST POST 丢失日期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20414275/

有关java - Android REST POST 丢失日期值的更多相关文章

  1. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  2. ruby-on-rails - date_field_tag,如何设置默认日期? [ rails 上的 ruby ] - 2

    我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问

  3. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

  4. ruby - 检查日期是否在过去 7 天内 - 2

    我的日期格式如下:"%d-%m-%Y"(例如,今天的日期为07-09-2015),我想看看是不是在过去的七天内。谁能推荐一种方法? 最佳答案 你可以这样做:require"date"Date.today-7 关于ruby-检查日期是否在过去7天内,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/32438063/

  5. ruby-on-rails - 将 Ruby 中的日期/时间格式化为 YYYY-MM-DD HH :MM:SS - 2

    这个问题在这里已经有了答案:Railsformattingdate(4个答案)关闭4年前。我想格式化Time.Now函数以显示YYYY-MM-DDHH:MM:SS而不是:“2018-03-0909:47:19+0000”该函数需要放在时间中.现在功能。require‘roo’require‘roo-xls’require‘byebug’file_name=ARGV.first||“Template.xlsx”excel_file=Roo::Spreadsheet.open(“./#{file_name}“,extension::xlsx)xml=Nokogiri::XML::Build

  6. ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等) - 2

    我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s

  7. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  8. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  9. ruby-on-rails - ruby 日期方程不返回预期的真值 - 2

    为什么以下不同?Time.now.end_of_day==Time.now.end_of_day-0.days#falseTime.now.end_of_day.to_s==Time.now.end_of_day-0.days.to_s#true 最佳答案 因为纳秒数不同:ruby-1.9.2-p180:014>(Time.now.end_of_day-0.days).nsec=>999999000ruby-1.9.2-p180:015>Time.now.end_of_day.nsec=>999999998

  10. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

随机推荐