我刚开始在一个项目中使用java,我有这个疑问。我试图用这段代码获得 JSON 答案,但我不知道如何在 Java Spring 中将字符串与函数连接起来。我有这个 Controller ,结果如下:
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
]
}
如果没有串联并仅返回 return 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
}
]
}
提前致谢
最佳答案
看起来 this.bbService.getAllContracts()
返回一个没有实现 toString()
的类,因此它得到了这个丑陋的默认打印,您可以实现它以获得您想要的更好的表示。
但我认为更好的解决方案不应该是修复 toString,而是将方法的返回值从字符串更改为您创建的某个类。如果你使用的是spring,一旦你这样做它就会被序列化成json
关于java - 将字符串与函数连接起来以获取 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60582039/