我有一个JPA投影,它返回这样的响应:

[
    {
        "active": 0,
        "created_at": "2023-11-07T18:06:56",
        "blocked": 0
    },
    {
        "active": 13,
        "created_at": "2023-12-07T18:06:56",
        "blocked": 0
    }
]

根据这一预测:

    List<CompaniesResult > result = .....;
    return new ResponseEntity<>(result, HttpStatus.OK);

    public interface CompaniesResult {
    
        LocalDateTime getCreated_at();
    
        Integer getActive();
    
        Integer getBlocked();
    }

我想像这样返回结果:

{
    "2023-11-07T18:06:56" : { "active": 0, "blocked": 0},
    "2024-11-07T18:06:56" : { "active": 20, "blocked": 10}
{

你知道我怎样才能转换这个Java列表吗?

推荐答案

我不确定你的确切要求,但我可能会以另一种方式返回它.但是如果你想这样返回它,你可以使用嵌套映射:

public ResponseEntity<Map<String, Map<String, Integer>>> companyResults() {
    List<CompaniesResult> result = ...; // 
    
    // Create a Map to store the converted data
    Map<String, Map<String, Integer>> convertedData = new HashMap<>();
    
    for (CompaniesResult company : result) {
        LocalDateTime createdAt = company.getCreated_at();
        Integer active = company.getActive();
        Integer blocked = company.getBlocked();
        
        Map<String, Integer> innerJson = new HashMap<>();
        innerJson.put("active", active);
        innerJson.put("blocked", blocked);
        
        convertedData.put(createdAt.toString(), innerJson);
    }
    
    // Return the map as a JSON response
    return new ResponseEntity<>(convertedData, HttpStatus.OK);
}

Java相关问答推荐

为什么JFrame paint()多次绘制同一点(或根本不绘制)?

Oracle DUAL表上使用DDL时jOOQ问题的解析'

Character::Emoji不支持带数字的字符吗?

Java FX中的河内之塔游戏-在游戏完全解决之前什么都不会显示

DTO到实体,反之亦然,控制器和服务之间的哪一层应该处理转换?

我找不到&Quot;配置&的位置

使用REST客户端和对象映射器从字符串反序列化Json

生成桥方法以解决具有相同擦除的冲突方法

如何在Application.yaml中连接字符串?

如何集成语义发布和BitBucket(Java项目)

Domino Designer 14中的保存代理添加了重影库

虚拟线程应该很快消亡吗?

允许同时执行两个方法,但不能同时执行这两个方法

是否为计划任务补偿系统睡眠?

如何在Spring Boot中创建可以将值传递给配置的&Enable&Quot;注释?

Java.lang.invke.LambdaConversionException:实例方法InvokeVirtual的参数数量不正确

AWS Java SDK v2.x中没有setObjectAcl方法

在应用getCellFormula()时,Excel引用中的文件名始终为";[1]";使用Apache POI()

如何在Maven Central上部署?

如何在 Android Studio 中删除 ImageView 和屏幕/父级边缘之间的额外空间?