我有一个复杂的对象,我想渲染它,但是我有几个问题。
首先,我有UUID字段在我的类,但在视图中,我得到的不是字符串,但mostSigBits和leastSigBits。第二个,我有我喜欢和枚举两个字段枚举字段和值
例如,
public class ExampleObject {
@JsonProperty("id")
private UUID id;
@JsonProperty("name")
private String name;
@JsonProperty("address")
private String address;
@JsonProperty("port")
private String port;
@JsonProperty("users")
@Valid
private List<UserRef> users = null;
@JsonProperty("indexingParameters")
private IndexingParameters indexingParameters;
@JsonProperty("otherParameters")
private OtherParameters otherParameters;
@JsonProperty("status")
private Status status;
}
当我从控制器得到响应时我得到的答案是这个
{
"id": {
"leastSignificantBits": -5406850341911646206,
"mostSignificantBits": 8884977146336383467
},
"status": {
"enumType": "api.model.Status",
"name": "GENERAL"
}
....
}
问题是我有很多不同的,但同样的问题对象在我的代码。如果只有一个对象,我很容易准备一些_exampleObject。gson模板并渲染从控制器到它的每个答案,但我有许多对象。
我认为有一些变体渲染正确我的JSON,不是吗?
另一个渲染变量data
是ExampleObject.class或类似的东西
1)代码:
Map map = [content: data.content, sorting: data.sorting, paging: data.paging] as Map
render AppResponse.success([success: true, data: map]).asJSON()
render data as JSON
在前:
Incorrect UUID and DateTime convert each field in Object, But I need Timeshtamp
"id": {"leastSignificantBits": -5005002633583312101,
"mostSignificantBits": 4056748206401340307},
"key": "b48d35dd-0551-4265-a1b1-65105e713811",
2)代码:
Map map = [data: new ObjectMapper().writeValueAsString(data)] as Map
render map
在前:
Here we can see square brackets at the start which is wrong for JSON
['data':'{"content":[{"id":"384c7700-09c1-4393-ba8a-a89f555f431b","name":"somename"...
3)代码:
Object result = new HashMap<String, Object>()
result.success = true
result["data1"] = new ObjectMapper().writeValueAsString(data)
render result as JSON
在前:
Here we can see quotes escaping
"data": "{"content":[{"id":"384c7700-09c1-4393-ba8a-a89f555f431b","name":"somename","key":"b48d35dd-0551-4265-a1b1-65105e713811","status":"COMPLETED.......
我是这样做的
@CompileStatic
class MyProxyController {
@Autowired
Myservice service
static ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new JodaModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
def getExampleObject {
ExampleObject exampleObject = service.getExampleObject()
render([contentType: "application/json"], objectMapper.writeValueAsString(new CustomObject(data, true)))
}
@CompileStatic
class CustomObject {
Boolean success
Object data
CustomObject(Object data, Boolean success) {
this.data = data
this.success = success
}
}
}
然后得到我想要的json,比如
{
"success": true,
"data": {
"content": [
{ ....