首页 > 解决方案 > 将字符串与函数连接以获取 JSON 输出

问题描述

我刚开始在一个项目中使用java,我有这个疑问。我正在尝试使用此代码获得 JSON 答案,但我不知道如何将字符串与 Java Spring 中的函数连接起来。我有这个控制器,结果如下:

public class BbController {
    @Autowired
    BbService bbService;

    private static final String RESP_SUCCESS =  "{\"result\" : { \"status\": true, \"http_code\" : 200, \"info\":  \"list successfully obtained.\"}}";

    @RequestMapping(value= "/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String getAllContracts() {
        return RESP_SUCCESS +  ",{" + this.bbService.getAllContracts() + "}";
    }
}

<---------- RESULT --------->>>
{
    "result": {
        "status": true,
        "http_code": 200,
        "info": "list successfully obtained."
    }
},
{
    [com.example.entity.BbEntity@3ddd5cfb, com.example.entity.BbEntity@1a57ff51
    ]
}

如果没有连接并且只返回返回 this.bbService.getAllContracts(),输出将是

[
    {
        "id": 12345,
        "id_client": 123,
        "n_contracts": 2,
        "default_number": 2
    },
    {
        "id": 1,
        "id_client": 12,
        "n_contracts": 2,
        "default_number": 2
    }
]

我的服务是

public class BbService {
    @Autowired
    BbDao bbDao;

    public List<BbEntity> getAllContracts(){
        return this.bbDao.findAll();
    }
}

有没有办法得到这个结果?

{
    "result": {
        "status": true,
        "http_code": 200,
        "info": "list successfully obtained."
    }
},
{
  [
    {
        "id": 12345,
        "id_client": 123,
        "n_contracts": 2,
        "default_number": 2
    },
    {
        "id": 1,
        "id_client": 12,
        "n_contracts": 2,
        "default_number": 2
    }
]
}

提前致谢

标签: javaspring

解决方案


看起来this.bbService.getAllContracts()返回一个没有实现的类toString(),因此它会得到这个丑陋的默认打印,你可以实现它以获得你想要的更好的表示。

但我认为更好的解决方案不应该是修复 toString,而是将方法的返回值从字符串更改为您创建的某个类。如果您使用的是spring,一旦您执行它将被序列化为json


推荐阅读