从java映射生成Json
我想从映射生成json格式的响应 我已经尝试了以下使用字符串作为键的Map,效果很好从java映射生成Json,java,json,Java,Json,我想从映射生成json格式的响应 我已经尝试了以下使用字符串作为键的Map,效果很好 private JsonNode build(Map<String, List<PlaylistUrl>> entitiesPlaylist) { JsonNode root = objectMapper.createObjectNode(); JsonNode data = objectMapper.createObjectNode();
private JsonNode build(Map<String, List<PlaylistUrl>> entitiesPlaylist) {
JsonNode root = objectMapper.createObjectNode();
JsonNode data = objectMapper.createObjectNode();
((ObjectNode) data).set(ENTITIES, objectMapper.valueToTree(entitiesPlaylist));
((ObjectNode) root).set(DATA, data);
return root;
}
私有JsonNode构建(映射实体播放列表){
JsonNode root=objectMapper.createObjectNode();
JsonNode data=objectMapper.createObjectNode();
((ObjectNode)data).set(ENTITIES,objectMapper.valueToTree(entitiesPlaylist));
((ObjectNode)root).set(数据,数据);
返回根;
}
但是,我现在有一个对象作为键而不是字符串,并且希望将该对象的所有值作为响应的一部分打印出来。我不确定在这里使用什么逻辑
private JsonNode build(Map<Entity, List<PlaylistUrl>> entitiesPlaylist) {
JsonNode root = objectMapper.createObjectNode();
JsonNode data = objectMapper.createObjectNode();
for (Map.Entry<Entity, List<PlaylistUrl>> entry: entitiesPlaylist.entrySet()) {
// what logic ?
}
((ObjectNode) root).set(DATA, data);
return root;
}
私有JsonNode构建(映射实体播放列表){
JsonNode root=objectMapper.createObjectNode();
JsonNode data=objectMapper.createObjectNode();
对于(Map.Entry:entitiesPlaylist.entrySet()){
//什么逻辑?
}
((ObjectNode)root).set(数据,数据);
返回根;
}
我需要响应来包含响应中的实体以及每个实体的播放列表数组列表。您的
构建方法在技术上可能类似于:
private JsonNode build(Map<Entity, List<PlayListUrl>> entitiesPlaylist) {
ArrayNode root = objectMapper.createArrayNode();
for (Map.Entry<Entity, List<PlayListUrl>> entry: entitiesPlaylist.entrySet()) {
JsonNode entityPlayListUrlsJsonObject = objectMapper.valueToTree(entry);
root.add(objectMapper.valueToTree(entityPlayListUrlsJsonObject));
}
return root;
}
如果我迟到了,我希望这对您或其他人有所帮助。使用这种结构有点困难,因为javascript对象只接受数字和字符串值作为键描述符,而您有一个复杂的对象作为键。相反,您可以创建一个{key:serializedEntity,value:serializedList}数组
我采用的方法是wring。我将播放列表嵌入实体类中,解决了问题。我采用的方法是错误的。我将播放列表嵌入实体类中,解决了问题。
[
{
"com.package.to.Entity@51931956": [
{
// First PlayListUrl object properties of this Entity
},
{
// Second PlayListUrl object properties of this Entity
},
...
]
},
{
"com.package.to.Entity@84569301": [
{
// First PlayListUrl object properties of this Entity
},
{
// Second PlayListUrl object properties of this Entity
}
...
]
},
...
]