如何将日期序列化为特定格式?

问题描述 投票:0回答:2

JSON 字符串中任意日期的强制输出格式为:

{
    "element": [
        "~#date",
        [
            "2013-05-31"
        ]
    ],
    ...
}

我必须遵守这个特定的格式。

用对象数组构建对象是行不通的。我得到这样的东西:

{
    "element": [
        {
            "~#date": "2024-09-17"
        }
    ],
    ...
}

我可以为 LocalDate 编写一个序列化程序来打印“[...]”。那种感觉就像是作弊。请注意,日期数始终为 1。

有这样做的标准方法吗?

这就是我到目前为止所做的: 该对象包含:

@JsonProperty("aDate")
private MyMDate[] myDate = null;

“MyDate”为:

@Setter
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MyDate {
    @JsonProperty("~#date")
    @JsonSerialize(using = LocalDateArraySerializer.class)
    private LocalDate[] date;
}

和序列化器:

public class LocalDateArraySerializer extends JsonSerializer<LocalDate[]> {
    private final DateTimeFormatter format = DateTimeFormatter.ofPattern( "yyyy-MM-dd");

    @Override
    public void serialize(LocalDate[] values, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String seperator = "";
        for ( LocalDate ld: values) {
            gen.writeString( seperator + ld.format(format));
            seperator = ",";
        }
    }
}

这给出了实际的输出:一个带有对象的数组。这不是所要求的输出。

java jackson jackson-databind
2个回答
1
投票

您可以使用以下方式存档:

public class Awkward implements Serializable {

    private static final long serialVersionUID = 1L;

    private Object[] element;

    public Awkward() {
        super();
        
        element = new Object[2];
        
        String awkwardDate = "~#date";
        element[0] = awkwardDate;

        String[] awkwardValue = new String[1];
        awkwardValue[0] = "2013-05-31";

        element[1] = awkwardValue;
    }
...

杰克逊将其序列化为:

{
  "element": [
    "~#date",
    ["2013-05-31"]
  ]
}

-1
投票

你只需要这些行:

public class CustomLocalDateSerializer extends StdSerializer<LocalDate> {

public CustomLocalDateSerializer() {
    super(LocalDate.class);
}

@Override
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    gen.writeStartArray();   // start outer array
    gen.writeString("~#date");
    gen.writeStartArray();   // start inner array
    gen.writeString(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); //date format
    gen.writeEndArray();     // end inner array
    gen.writeEndArray();     // end outer array
    }
}

@JsonSerialize(using = CustomLocalDateSerializer.class)
public class DateHolder {
private LocalDate date;

public DateHolder(LocalDate date) {
    this.date = date;
}

// getters and setters
}

然后调用自定义序列化器

ObjectMapper mapper = new ObjectMapper();

DateHolder dateHolder = new DateHolder(LocalDate.of(2013, 5, 31));
    String json = mapper.writeValueAsString(dateHolder); //serialize
System.out.println(json);
© www.soinside.com 2019 - 2024. All rights reserved.