Java Concat一个字符串,并使用一个函数获取JSON输出
我刚刚开始在一个项目中使用java,我对此表示怀疑。我试图用这段代码得到一个JSON答案,但我不知道如何在JavaSpring中将字符串与函数连接起来。我有一个控制器,结果如下:Java Concat一个字符串,并使用一个函数获取JSON输出,java,spring,Java,Spring,我刚刚开始在一个项目中使用java,我对此表示怀疑。我试图用这段代码得到一个JSON答案,但我不知道如何在JavaSpring中将字符串与函数连接起来。我有一个控制器,结果如下: public class BbController { @Autowired BbService bbService; private static final String RESP_SUCCESS = "{\"result\" : { \"status\": true, \"http_c
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
]
}
我的服务是
public class BbService {
@Autowired
BbDao bbDao;
public List<BbEntity> getAllContracts(){
return this.bbDao.findAll();
}
}
提前感谢看起来像
这个.bbService.getAllContracts()
返回一个没有实现toString()
的类,因此它会得到这个丑陋的默认打印,您可以实现它以获得您想要的更好的表示
但我认为更好的解决方案不应该是修复toString,而是将方法的返回值从字符串更改为您创建的某个类。如果您使用的是spring,那么一旦您使用它,它将被序列化为json看起来像
this.bbService.getAllContracts()
返回一个未实现toString()
的类,因此它会得到这个丑陋的默认打印,您可以实现它以获得您想要的更好的表示
但我认为更好的解决方案不应该是修复toString,而是将方法的返回值从字符串更改为您创建的某个类。如果您使用的是spring,那么一旦您使用spring,它就会被序列化为json。如果
this.bbService.getAllContracts()
,getAllContracts()
返回它自己的类,它会自动序列化为json。如果this.bbService.getAllContracts()
,getAllContracts()
返回它自己的类,它将自动序列化为Json。你能给我举个例子吗?我对java和JavaSpring非常陌生,我有点迷路了。你可以看到他们是如何返回一个对象的,它会被序列化,你可以给我一个例子吗?我对java和JavaSpring非常陌生,我有点迷路了。你可以看到他们是如何返回一个对象的,它会被序列化
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
}
]
}