gpt4 book ai didi

java - Gson 中是否有 JsonFormat 的类似物?

转载 作者:行者123 更新时间:2023-12-03 23:13:29 26 4
gpt4 key购买 nike

我的问题真的很小:

我比 fastrxml.jackson 更喜欢 Gson。我希望在 Gson 中看到的一个可能的功能是:

//some code
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
private Date endDate;
//some code

我发现在 Gson 中做同样事情的唯一方法是:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();

我认为注释比初始化更容易理解。
有什么方法可以注释或制作一些属性,以便代码
gson.fromJson("\"{\\\"Id\\\": 703,\\\"StartDate\\\": \\\"2019-10-01T00:00:00\\\"," +
" \\\"EndDate\\\": \\\"2019-10-25T00:00:00\\\",\\\"Title\\\": \\\"exmample title\\\"}\"",
MyObj.class)

将产生类 MyObj 的对象:
public class MyObj{
@SerializedName("Id")
private Long id;
@SerializedName("StartDate")
//analogue of JsonFormat????
private Date startDate;
@SerializedName("EndDate")
//analogue of JsonFormat????
private Date endDate;
@SerializedName("Title")
private String title;
}

最佳答案

要将 JSON 反序列化为 POJO Gson 使用标记为 com.google.gson.internal.bind.ReflectiveTypeAdapterFactoryfinal 类。要处理额外的注释,您必须实现类似的东西,并创建新的注释并在反序列化逻辑中处理它。现在,您可以实现您的自定义 com.google.gson.JsonDeserializer 来解析给定的日期。

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;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class GsonApp {

public static void main(String[] args) {
Gson gson = new GsonBuilder().create();
MyObj myObj = gson.fromJson(
"{\"Id\": 703,\"StartDate\": \"2019-10-01T00:00:00\",\"EndDate\": \"2019-10-25T00:00:00\",\"Title\": \"exmample title\"}",
MyObj.class);
System.out.println(myObj);
}
}

class IsoDateTimeJsonDeserializer implements JsonDeserializer<Date> {

@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
LocalDateTime localDateTime = LocalDateTime.parse(json.getAsString(), DateTimeFormatter.ISO_DATE_TIME);

return Date.from(localDateTime.atZone(ZoneOffset.systemDefault()).toInstant());
}
}

class MyObj {

@SerializedName("Id")
private Long id;

@SerializedName("StartDate")
@JsonAdapter(IsoDateTimeJsonDeserializer.class)
private Date startDate;

@SerializedName("EndDate")
@JsonAdapter(IsoDateTimeJsonDeserializer.class)
private Date endDate;

@SerializedName("Title")
private String title;

// getters, setters, toString
}

上面的代码打印:
MyObj{id=703, startDate=Tue Oct 01 00:00:00 CEST 2019, endDate=Fri Oct 25 00:00:00 CEST 2019, title='exmample title'}

关于java - Gson 中是否有 JsonFormat 的类似物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58609109/

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