java - 如何将对象转换为 Map 样式 JSON 以通过 Spring 中的 Get 请求发送?

标签 java json spring get

对象模型:

public class NotificationSettingsDto {

private Boolean campaignEvents;
private Boolean drawResultEvents;
private Boolean transactionEvents;
private Boolean userWonEvents;
}

假设我正在获取这个对象

new NotificationSettingsDto(true,true,true,true);

通过spring get请求。

这是我想从该对象获取的 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}]

关于java - 如何将对象转换为 Map 样式 JSON 以通过 Spring 中的 Get 请求发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44459010/

相关文章:

java - FocusEvent 没有获取 JFormattedTextField 的最后一个值,我如何获取它?

java - 如何让JComboBox响应回车键

Spring批处理暂停/恢复与停止/重启

java - Bean 不在 JNDI 中

java - Spring boot 在 tomcat 上部署为 WAR,如何为不同的配置文件外部化 application.properties(Dev、Test、Staging、Prod)

java - 定时器在满足条件时给出错误

java - 如何从Firebase实时数据库获取两个变量

javascript - 修改JSON数据

java - REST Jersey 客户端 - 无法将 JSON 解析为 POJO 类

json - 如何让 Spark 将 JSON 转义字符串字段解析为 JSON 对象以推断数据帧中的正确结构?