java - 将字符串与函数连接以获取 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
}
]
}
提前致谢
解决方案
看起来this.bbService.getAllContracts()
返回一个没有实现的类toString()
,因此它会得到这个丑陋的默认打印,你可以实现它以获得你想要的更好的表示。
但我认为更好的解决方案不应该是修复 toString,而是将方法的返回值从字符串更改为您创建的某个类。如果您使用的是spring,一旦您执行它将被序列化为json
推荐阅读
- android - 将 Play Services 升级到 15.0.0 后出现 MergerException: Unable to merge dex while running
- oracle - 无法从 12c 中的 V$RMAN_BACKUP_JOB_DETAILS 取回任何行
- android - 当用户在 Activity Android 中输入时间过长时自动重定向
- ms-access - 在访问vba中从for循环内的每个表中动态删除一行
- java - 如何在一行中通过特定属性对象Java8将arraylist拆分为多个列表
- elasticsearch - Elasticsearch 对衍生聚合进行排序以查找趋势主题
- ruby-on-rails - Rspec - 检查特定模型的 ActiveRecord::Relation 实例
- c# - 使用 EFCore.BulkExtensions 时是否需要调用 SaveChanges
- git - 如何让 git 理解 Mac (CR) 行尾
- c# - 通过 WebApi 获取本地映射文件或目录的 TFS 信息