Вот код < /strong>:
Код: Выделить всё
DatePair
Код: Выделить всё
import lombok.Data;
import java.util.Date;
@Data
public class DatePair {
Date date1;
Date date2;
}
< /code>
Мой пример: < /p>
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import lombok.Data;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Data
public class Example {
@Data
public static class Model1 {
@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss.SSS", timezone = "GMT+2")
DatePair datePair;
}
public static class DatePairJsonSerializer extends JsonSerializer {
@Override
public void serialize(DatePair value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeRaw("(");
serializers.defaultSerializeValue(value.date1, gen);
gen.writeRaw(", ");
/*
When serialize Model1
will throw JsonGenerationException: Can not write a string, expecting field name (context: Object)
*/
serializers.defaultSerializeValue(value.date2, gen);
gen.writeRaw(")");
}
}
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(DatePair.class, new DatePairJsonSerializer());
mapper.registerModule(simpleModule);
DatePair datePair = new DatePair();
datePair.setDate1(new Date());
datePair.setDate2(new Date());
Model1 model1 = new Model1();
model1.setDatePair(datePair);
try {
/*
serialize DatePair
*/
String json = mapper.writeValueAsString(datePair);
System.out.println(json); // output: ("2025-06-22 10:02:48", "2025-06-22 10:02:48")
/*
serialize Model1
will throw JsonGenerationException: Can not write a string, expecting field name (context: Object)
*/
json = mapper.writeValueAsString(model1); // expected output: {"datePair": "(2025/06/22 10:02:48.000, 2025/06/22 10:02:48.000)"}
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
< /code>
Зависимости: < /p>
com.fasterxml.jackson.core
jackson-databind
2.18.2
[*] Когда сериализует Datepair , я хочу, чтобы дата вывода не имел цитат, например: (2025-06-22 10:02:48, 2025-06-22 10:02:48)
Подробнее здесь: https://stackoverflow.com/questions/796 ... -string-us