我有跟随传入的json,我将其反序列化为Model.java,然后将该java对象复制到ModelView.java。我不想将日期从String转换为毫秒,并将Outgoing json作为响应发送。 我该怎么做?
我有特殊的理由使用对象映射器将Model.java中的值复制到ModelView.java。所以请不要建议修改那部分。我希望通过注释来做到这一点。我很确定它可以完成,但不知道如何。
这里提供的json是一个简单的。在实际场景中我有一个大型的json。
传入的json
{
"date":"2016-03-31"
}
离开Json
{
"date":236484625196
}
我的控制器类
@Controller
public class SomeController extends BaseController {
@Autowired
private SomeService someService;
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody
ResponseEntity<RestResponse> getDetails(HttpServletRequest request, HttpServletResponse response) {
Model model = someService.getData();
ModelView modelView = ModelView.valueOf(model);
return getSuccessResponse(modelView);
}
}
Model.java
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Model implements Serializable {
private String date;
//normal getters and setters
}
ModelView.java
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ModelView implements Serializable {
private Long date;
//normal getters and setters
public static ModelView valueOf(Model model){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
ObjectMapper mapper = new ObjectMapper();
ModelView modelView = mapper.convertValue(model, ModelView.class);
try {
modelView.setDate(sdf.parse(model.getDate()).getTime());
} catch (ParseException e) {
IntLogger.error("logging error here");
}
return modelView;
}
}
我愿意将变量名称从“date”更改为ModelView.java中的其他名称,但传出的json应保持相同。
答案 0 :(得分:1)
更简单的日期序列化和反序列化方法,如果您希望序列化和反序列化为不同的格式,则直接在Model.class上使用@JsonSerialize和@JsonDeserialize注释(如果您的唯一目的,这可能会淘汰ModelView的需求是转换日期)。
您可以为序列化和反序列化创建两个类:
public class JsonDateDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = jsonParser.getText();
try {
return dateFormat.parse(dateString);
}
catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
然后序列化你的Outgoing json:
public class JsonDateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeString(Long.toString(date.getTime()));
}
}
现在,您只需注释您的Model.java:
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Model implements Serializable {
@JsonSerialize(using = JsonDateSerializer.class)
@JsonDeserialize(using = JsonDateDeserializer.class)
private String date;
//normal getters and setters
}