在我们春季配置的休息器中,我们使用杰克逊将对象转换为JSON。该对象包含几个java.util.date对象。

当我们尝试使用GSON的FromJSON方法在Android设备上进行对其进行启用,我们将获得“ Java.text.parseexception:Untarsable Date”。我们已经尝试将日期序列化到1970年以来与毫秒相对应的时间戳,但得到同样的例外。

是否可以将GSON配置为将时间戳格式的日期(例如1291158000000)解析为java.util.date对象?

有帮助吗?

解决方案

您需要注册自己的避难所以获取日期。

我在下面创建了一个小示例,其中JSON字符串“ 23-11-2010 10:00:00”被划分为日期对象:

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;


public class Dummy {
    private Date date;

    /**
     * @param date the date to set
     */
    public void setDate(Date date) {
        this.date = date;
    }

    /**
     * @return the date
     */
    public Date getDate() {
        return date;
    }

    public static void main(String[] args) {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {

                SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                String date = json.getAsJsonPrimitive().getAsString();
                try {
                    return format.parse(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Gson gson = builder.create();
        String s = "{\"date\":\"23-11-2010 10:00:00\"}";
        Dummy d = gson.fromJson(s, Dummy.class);
        System.out.println(d.getDate());
    }
}

其他提示

关于杰克逊,您不仅可以在数字(TIMESTAMP)和文本序列化(serializationConfig.feature.write.write_dates_as_as_timestamps)之间进行选择,还可以定义用于文本变体的精确dateformat(serializationConfig.setDateFormat)。因此,如果不支持ISO-8601格式杰克逊默认值,您应该能够强制使用GSON识别的东西。

另外:杰克逊在Android上工作正常,如果您不介意在Gson上使用它。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top