2017-06-09 2 views
0

オブジェクトモデル: オブジェクトをMapスタイルのJSONに変換して、SpringでGetリクエストを送信するにはどうすればよいですか?

public class NotificationSettingsDto { 

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

は、私は春のGETリクエストでこのオブジェクト

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

を取得していたとします。

これは私がこのオブジェクトから取得したいJSON値です。

[{"name" : "campaignEvents" , "value" : true}, 
{"name" : "drawResultEvents" , "value" : true}, 
{"name" : "transactionEvents" , "value" : true}, 
{"name" : "userWonEvents", "value" : true}] 
+0

はあなただけ手動で作成することができませんか?別のクラスを取り、必要なjson形式を作成するクラスを言う。 – nafas

+0

あなたの投稿に入れたJSONは無効です。それがちょうどタイプミスかそれを意味するか明確にしてください。 –

+0

@nafasありがとう!他は私に同じ手がかりを与えました。私の答えをチェックしてください。 – Amiko

答えて

2

これは、それを解決:NotificationSettingsDtoの略nsDto

Arrays.asList( new CustomPair<>("campaignEvents", nsDto.getCampaignEvents()), 
       new CustomPair<>("drawResults", nsDto.getDrawResultEvents()), 
       new CustomPair<>("transactionEvents", nsDto.getTransactionEvents()), 
       new CustomPair<>("userWonEvents", nsDto.getUserWonEvents()) 

を。 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}] 
+0

あなたは要件が大好き! – Steve11235

+0

@ Steve11235、そうですね、それは時には私たちを汚れた解決に導きます。 :( – Amiko

2

Jackson 2.x ObjectMapperクラスを使用できます。

NotificationSettingsDto obj = new NotificationSettingsDto(true,true,true,true); 
ObjectMapper mapper = new ObjectMapper(); 
String jsonString = mapper.writeValueAsString(obj); 

あなたのjson文字列は無効です。

{ 
    "campaignEvents": true, 
    "drawResultEvents": true, 
    "transactionEvents": true, 
    "userWonEvents": true 
} 

EDIT:これはあなたのJSONは次のようになりますどのようにあるコメントで述べたようにまた、それはGsonを使用して行うことができます。

Gson gson = new Gson(); 
NotificationSettingsDto obj = new NotificationSettingsDto(true,true,true,true); 
String jsonString = gson.toJson(obj); 
+0

私はGsonを好むが、Roxana Romanが提供したものは正しいと思う。 – Steve11235

+0

@ Steve11235はい、正しいフォーマットです。同意する。答えをありがとう。私はそのようにしていましたが、質問に投稿した方法を具体的に求められました。私は自分の質問にタイプを修正し、答えを掲載しました。見てみな。 – Amiko

関連する問題