对象模型:
public class NotificationSettingsDto {
private Boolean campaignEvents;
private Boolean drawResultEvents;
private Boolean transactionEvents;
private Boolean userWonEvents;
}
说我得到了这个对象
new NotificationSettingsDto(true,true,true,true);
通过春天获取请求。
这是我想从这个对象获得的JSON值。
[{"name" : "campaignEvents" , "value" : true},
{"name" : "drawResultEvents" , "value" : true},
{"name" : "transactionEvents" , "value" : true},
{"name" : "userWonEvents", "value" : true}]
答案 0 :(得分:3)
这解决了它:
Arrays.asList( new CustomPair<>("campaignEvents", nsDto.getCampaignEvents()),
new CustomPair<>("drawResults", nsDto.getDrawResultEvents()),
new CustomPair<>("transactionEvents", nsDto.getTransactionEvents()),
new CustomPair<>("userWonEvents", nsDto.getUserWonEvents())
nsDto
代表NotificationSettingsDto
。而CustomPair
是:
public class CustomPair<K, V> {
private K key;
private V value;
}
@nafas在评论部分是正确的。谢谢。它不是最干净的解决方案,但确实如此
结果JSON:
[{"key":"campaignEvents","value":true},
{"key":"drawResults","value":true},
{"key":"transactionEvents","value":true},
{"key":"userWonEvents","value":true}]
答案 1 :(得分:2)
您可以使用Jackson 2.x ObjectMapper类。
NotificationSettingsDto obj = new NotificationSettingsDto(true,true,true,true);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(obj);
但是你的json字符串无效。这就是你的json的样子:
{
"campaignEvents": true,
"drawResultEvents": true,
"transactionEvents": true,
"userWonEvents": true
}
编辑:您也可以使用评论中提到的Gson。
Gson gson = new Gson();
NotificationSettingsDto obj = new NotificationSettingsDto(true,true,true,true);
String jsonString = gson.toJson(obj);