我需要将Joda DateTime序列化为JSON作为单个字符串。我使用JsonSerializer的实现,它假设生成字符串,但我得到的对象有很多属性:
"metrics":{"startTimestamp":{"year":2014,"dayOfMonth":11,"dayOfWeek":2,"era":1,"dayOfYear":315,"centuryOfEra":20,"yearOfCentury":14,"monthOfYear":11,"weekOfWeekyear":46,"millisOfSecond":505,"millisOfDay":36348505,"secondOfMinute":48,"secondOfDay":36348,"minuteOfHour":5,.......... etc
但我需要像dd.mm.yyyy HH:mm:ss.SSS
这样的字符串。怎么做?
CustomDateSerializer
public class CustomDateSerializer extends JsonSerializer<DateTime> {
private static DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss.SSS");
@Override
public void serialize(DateTime value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException {
gen.writeString(formatter.print(value));
// System.out.println(formatter.print(value));
}
@Override
public Class<DateTime> handledType() {
return DateTime.class;
}
}
度量
import app.service.CustomDateSerializer;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
public class Metrics {
// @JsonSerialize(using = CustomDateSerializer.class)
DateTime startTimestamp;
// @JsonSerialize(using = CustomDateSerializer.class)
DateTime endTimestamp;
Period period;
@JsonIgnore
PeriodFormatter periodFormatter;
public Metrics() {
}
public DateTime getStartTimestamp() {
return startTimestamp;
}
public void setStartTimestamp(DateTime startTimestamp) {
this.startTimestamp = startTimestamp;
}
public DateTime getEndTimestamp() {
return endTimestamp;
}
public void setEndTimestamp(DateTime endTimestamp) {
this.endTimestamp = endTimestamp;
}
public Period getPeriod() {
return period;
}
public void setPeriod() {
this.period = new Period(this.startTimestamp, this.endTimestamp);
}
public void setPeriod(Period period) {
this.period = period;
}
public PeriodFormatter getPeriodFormatter() {
return periodFormatter;
}
public void setPeriodFormatter(PeriodFormatter periodFormatter) {
this.periodFormatter = periodFormatter;
}
@Override
public String toString(){
this.periodFormatter = new PeriodFormatterBuilder()
.printZeroAlways()
.minimumPrintedDigits(2)
.appendHours().appendSeparator(":")
.appendMinutes().appendSeparator(":")
.appendSeconds().appendSeparator(".")
.appendMillis3Digit()
.toFormatter();
return "Started: " + this.startTimestamp.toString() + "\\n" + "Ended: " + this.endTimestamp.toString() + "\\n" + "Response took: " + periodFormatter.print(period)+ "";
}
}
更新
System.out.println(formatter.print(value))
中的{p> CustomDateSerializer
实际打印出正确的字符串但由于某种原因未能将其传递给序列化程序,我认为.....
UPDATE2
控制器
public @ResponseBody XmlResponse getGUID( @RequestParam(/*...*/) String environmentParam) {
//.... XmlResponse xmlResponse = ..........
return xmlResponse;
}
XmlResponse类
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
public class XmlResponse {
String xmlResponseBody;
@JsonIgnore
Metrics metrics;
Boolean error;
public XmlResponse() {
}
public XmlResponse(String xmlResponseBody, Metrics metrics, Boolean error) {
this.xmlResponseBody = xmlResponseBody;
this.metrics = metrics;
this.error = error;
}
public String getXmlResponseBody() {
return xmlResponseBody;
}
public void setXmlResponseBody(String xmlResponseBody) {
this.xmlResponseBody = xmlResponseBody;
}
@JsonProperty("metrics")
public Metrics getMetrics() {
return metrics;
}
public void setMetrics(Metrics metrics) {
this.metrics = metrics;
}
public Boolean getError() {
return error;
}
public void setError(Boolean error) {
this.error = error;
}
@Override
public String toString(){
String out = "";
ObjectMapper mapper = new ObjectMapper();
try {
// mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// mapper.registerModule(new JodaModule());
out = mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
return "{}";
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
}
UPDATE3
取消注释@JsonSerialize(using = CustomDateSerializer.class)
不会更改结果
答案 0 :(得分:1)
你的代码是Jackson 1.x(org.codehaus.jackson
)和Jackson 2.x(com.fasterxml.jackson
)的混合体。虽然他们的API非常相似,但Jackson 1.x的注释对Jackson 2.x没有影响,反之亦然(除非你使用jackson-legacy-introspector)。
确保您在任何地方使用相同的Jackson版本应该有助于解决您的问题 您可以在那里获得更多信息:Upgrading Jackson 1.9 to 2.0。