假设我有3个不同的日期,如下所示:
try {
DateDetails GetDateDetailsResp = GET.getDateDetails;
Date date1 = GetDateDetailsResp.dateDetails.date1;
Date date2 = GetDateDetailsResp.dateDetails.date2;
Date date3 = GetDateDetailsResp.dateDetails.date3;
}
我需要使用以下命令将它们全部返回为一个JSON
对象:
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(JSONobject);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonString);
所以我如何用JSONobject映射3个日期以作为一个JSON对象返回。
答案 0 :(得分:1)
这是比我的第一个答案最好的解决方法。
@Data
public static class ResponseVo {
private Object1 obj1;
private Object2 obj2;
public static ResponseVo getInstance(Object1 obj1, Object2 obj2) {
ResponseVo vo = new ResponseVo();
vo.setObj1(obj1);
vo.setObj2(obj2);
return vo;
}
}
@Data
public static class Object1{
private String object1String;
private Integer object1Integer;
}
@Data
public static class Object2 {
private String object2String;
private Integer object2Integer;
private Object1 object2Obj;
}
@GetMapping(value = "/test")
public ResponseEntity<ResponseVo> test() {
Object1 object1 = new Object1();
object1.setObject1Integer(1);
object1.setObject1String("obj1");
Object2 object2 = new Object2();
object2.setObject2String("obj2");
object2.setObject2Integer(2);
object2.setObject2Obj(object1);
return new ResponseEntity<>(ResponseVo.getInstance(object1, object2), HttpStatus.OK);
}
这是json数据。
{
"obj1": {
"object1String": "obj1",
"object1Integer": 1
},
"obj2": {
"object2String": "obj2",
"object2Integer": 2,
"object2Obj": {
"object1String": "obj1",
"object1Integer": 1
}
}
}
这是另一个解决方案。
@Data
public static class Object1{
private String object1String;
private Integer object1Integer;
}
@Data
public static class Object2 {
private String object2String;
private Integer object2Integer;
private Object1 object2Obj;
}
@GetMapping(value = "/test")
public ResponseEntity<Map> test() {
Object1 object1 = new Object1();
object1.setObject1Integer(1);
object1.setObject1String("obj1");
Object2 object2 = new Object2();
object2.setObject2String("obj2");
object2.setObject2Integer(2);
object2.setObject2Obj(object1);
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.convertValue(object1, Map.class);
map.putAll(mapper.convertValue(object2, Map.class));
return new ResponseEntity<>(map, HttpStatus.OK);
}
这是json数据。
{
"object1String": "obj1",
"object1Integer": 1,
"object2String": "obj2",
"object2Integer": 2,
"object2Obj": {
"object1String": "obj1",
"object1Integer": 1
}
}