gpt4 book ai didi

java - Gson Postgres 时间戳序列化

转载 作者:行者123 更新时间:2023-11-29 13:21:55 24 4
gpt4 key购买 nike

问题出在使用 GSON 的 Postegres 时间戳序列化中,

private static final GsonBuilder GSON_BASE = Converters
.registerAll(new GsonBuilder().disableHtmlEscaping())
.registerTypeAdapter(InfoTransfer.class, new InfoTransfer.Adapter())
.setDateFormat(DateFormat.FULL, DateFormat.FULL) //Line added but it seems work for MySQL DB Timestamp
.setPrettyPrinting()
.create();
.
//inner class in InfoTransfer
public static class Adapter implements JsonSerializer<InfoTransfer>{

@Override
public JsonElement serialize(InfoTransfer src, Type typeOfSrc, JsonSerializationContext context) {

Gson gson= new Gson();
JsonObject jsonObject= (JsonObject) gson.toJsonTree(src);

return new JsonPrimitive(jsonObject.getAsString());
}
}
.
.
.
Log.d("Result",GSON_BASE.toJson(data));

预期结果:

"created_at": "2016-10-13 18:18:51.64208+01"

结果:

\"created_at\": \"\\u0000\\u0001\\ufffdM\\u0015q\\ufffd}\"

有什么建议吗?

最佳答案

日期格式可以设置如下:-

setDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSX")

示例:-

public static void main(String[] args) {

String jsonString = "{\"customorId\":\"506\",\"joiningDate\":\"2016-10-26 19:49:17.290671+01\"}";

Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSX")
.setPrettyPrinting()
.create();


//Deserialize
Customer customer = gson.fromJson(jsonString, Customer.class);
System.out.println(customer.toString());

//Serialize
Customer customerSerialize = new Customer();
customerSerialize.setCustomorId("123");
customerSerialize.setJoiningDate(new Date());

System.out.println(gson.toJson(customerSerialize));


}

客户类别:-

public class Customer implements Serializable {
private static final long serialVersionUID = 1100012615187080642L;

private String customorId;

private Date joiningDate;

}

示例输出:-

Customer [customorId=506, joiningDate=Wed Oct 26 19:54:07 BST 2016]
{
"customorId": "123",
"joiningDate": "2016-10-26 20:23:37.000811+01"
}

关于java - Gson Postgres 时间戳序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40261480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com