Reputation: 585
Object Model:
public class NotificationSettingsDto {
private Boolean campaignEvents;
private Boolean drawResultEvents;
private Boolean transactionEvents;
private Boolean userWonEvents;
}
Say I'm getting this object
new NotificationSettingsDto(true,true,true,true);
through spring get request.
And this is the JSON value I want to get from this object.
[{"name" : "campaignEvents" , "value" : true},
{"name" : "drawResultEvents" , "value" : true},
{"name" : "transactionEvents" , "value" : true},
{"name" : "userWonEvents", "value" : true}]
Upvotes: 0
Views: 73
Reputation: 585
This solved it :
Arrays.asList( new CustomPair<>("campaignEvents", nsDto.getCampaignEvents()),
new CustomPair<>("drawResults", nsDto.getDrawResultEvents()),
new CustomPair<>("transactionEvents", nsDto.getTransactionEvents()),
new CustomPair<>("userWonEvents", nsDto.getUserWonEvents())
nsDto
stands for NotificationSettingsDto
. Whereas CustomPair
is:
public class CustomPair<K, V> {
private K key;
private V value;
}
@nafas was right in the comment section. Thanks. It's not the cleanest Solution but it does it
Resulted JSON :
[{"key":"campaignEvents","value":true},
{"key":"drawResults","value":true},
{"key":"transactionEvents","value":true},
{"key":"userWonEvents","value":true}]
Upvotes: 3
Reputation: 1012
You can use Jackson 2.x ObjectMapper class.
NotificationSettingsDto obj = new NotificationSettingsDto(true,true,true,true);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(obj);
But your json string is not valid. This is how your json would look like:
{
"campaignEvents": true,
"drawResultEvents": true,
"transactionEvents": true,
"userWonEvents": true
}
EDIT: You can also do it using Gson as mentioned in the comment.
Gson gson = new Gson();
NotificationSettingsDto obj = new NotificationSettingsDto(true,true,true,true);
String jsonString = gson.toJson(obj);
Upvotes: 2