对象模型:
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}]
这解决了它:
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}]
您可以使用 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);