如何在Spring Boot中获取定制的JSON对象响应。

huangapple go评论77阅读模式
英文:

How to get customize JSON object response in spring boot

问题

{
    "packId": 12,
    "packType": "sdf",
    "shortCode": "dfsdf",
    "packDescription": "fsdfd",
    "startDate": null,
    "endDate": null,
    "validityValue": 30,
    "validityType": "Second",
    "expiryAction": true,
    "expiryMsg": 64,
    "activationSMS": 63,
    "deactivationAction": true,
    "deactivationShortCode": "fhhf",
    "deactivationSMS": 64,
    "deprovisionOnExpiry": true,
    "timeBands": [
        {
            "start": "10:00",
            "end": "22:00"
        },
        {
            "start": "12:00",
            "end": "20:00"
        }
    ],
    "activationTypes": [
        "SMS",
        "WEB",
        "Channel"
    ],
    "channels": [
        "Hshenid",
        "Genisis",
        "Selfcare"
    ],
    "users": [
        "Selfcare"
    ]
}
@Override
public Optional<Pack> findById(int id) {
    return packRepository.findById(id);
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int packId;

String packType;
String shortCode;
String packDescription;
String startDate;
String endDate;
int validityValue;
String validityType;
Boolean expiryAction;
int expiryMsg;
int activationSMS;
Boolean deactivationAction;
String deactivationShortCode;
int deactivationSMS;
Boolean deprovisionOnExpiry;

@ManyToMany(cascade = {CascadeType.MERGE})
@JoinTable(name = "PacksTimeBands",
        joinColumns = @JoinColumn(name = "pack_id", referencedColumnName = "packId"),
        inverseJoinColumns = @JoinColumn(name = "timeband_id", referencedColumnName = "timeBandId"),
        uniqueConstraints = {@UniqueConstraint(columnNames = {"pack_id", "timeband_id"})})
List<TimeBand> timeBands;

@ManyToMany(cascade = {CascadeType.MERGE})
@JoinTable(name = "PacksActivationTypes",
        joinColumns = @JoinColumn(name = "pack_id", referencedColumnName = "packId"),
        inverseJoinColumns = @JoinColumn(name = "activationtype_id", referencedColumnName = "activationTypeId"),
        uniqueConstraints = {@UniqueConstraint(columnNames = {"pack_id", "activationtype_id"})})
List<ActivationType> activationTypes;

@ManyToMany(cascade = {CascadeType.MERGE})
@JoinTable(name = "PacksChannels",
        joinColumns = @JoinColumn(name = "pack_id", referencedColumnName = "packId"),
        inverseJoinColumns = @JoinColumn(name = "channel_id", referencedColumnName = "channelId"),
        uniqueConstraints = {@UniqueConstraint(columnNames = {"pack_id", "channel_id"})})
List<Channel> channels;

@ManyToMany(cascade = {CascadeType.MERGE})
@JoinTable(name = "PacksUsers",
        joinColumns = @JoinColumn(name = "pack_id", referencedColumnName = "packId"),
        inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "userId"),
        uniqueConstraints = {@UniqueConstraint(columnNames = {"pack_id", "user_id"})})
List<User> users;
英文:

I need to need to get customized JSON object rather than default one in Spring Boot. I could successfully get default response but I need to customize as below. Some objects needed to be converted to array and some fields should be removed.

Actual Response

{
&quot;packId&quot;:12,
&quot;packType&quot;:&quot;sdf&quot;,
&quot;shortCode&quot;:&quot;dfsdf&quot;,
&quot;packDescription&quot;:&quot;fsdfd&quot;,
&quot;startDate&quot;:null,
&quot;endDate&quot;:null,
&quot;validityValue&quot;:30,
&quot;validityType&quot;:&quot;Second&quot;,
&quot;expiryAction&quot;:true,
&quot;expiryMsg&quot;:64,
&quot;activationSMS&quot;:63,
&quot;deactivationAction&quot;:true,
&quot;deactivationShortCode&quot;:&quot;fhhf&quot;,
&quot;deactivationSMS&quot;:64,
&quot;deprovisionOnExpiry&quot;:true,
&quot;timeBands&quot;:[
{
&quot;timeBandId&quot;:1,
&quot;start&quot;:&quot;10:00&quot;,
&quot;end&quot;:&quot;22:00&quot;,
&quot;timeBand&quot;:&quot;10:00-22:00&quot;
},
{
&quot;timeBandId&quot;:2,
&quot;start&quot;:&quot;12:00&quot;,
&quot;end&quot;:&quot;20:00&quot;,
&quot;timeBand&quot;:&quot;12:00-20:00&quot;
}
],
&quot;activationTypes&quot;:[
{
&quot;activationTypeId&quot;:1,
&quot;name&quot;:&quot;SMS&quot;
},
{
&quot;activationTypeId&quot;:2,
&quot;name&quot;:&quot;WEB&quot;
},
{
&quot;activationTypeId&quot;:3,
&quot;name&quot;:&quot;Channel&quot;
}
],
&quot;channels&quot;:[
{
&quot;channelId&quot;:1,
&quot;name&quot;:&quot;Hshenid&quot;
},
{
&quot;channelId&quot;:2,
&quot;name&quot;:&quot;Genisis&quot;
}
],
&quot;users&quot;:[
{
},
{
&quot;userId&quot;:2,
&quot;name&quot;:&quot;Selfcare&quot;
}
]
}

Expected Response

{
&quot;packId&quot;: 12,
&quot;packType&quot;: &quot;sdf&quot;,
&quot;shortCode&quot;: &quot;dfsdf&quot;,
&quot;packDescription&quot;: &quot;fsdfd&quot;,
&quot;startDate&quot;: null,
&quot;endDate&quot;: null,
&quot;validityValue&quot;: 30,
&quot;validityType&quot;: &quot;Second&quot;,
&quot;expiryAction&quot;: true,
&quot;expiryMsg&quot;: 64,
&quot;activationSMS&quot;: 63,
&quot;deactivationAction&quot;: true,
&quot;deactivationShortCode&quot;: &quot;fhhf&quot;,
&quot;deactivationSMS&quot;: 64,
&quot;deprovisionOnExpiry&quot;: true,
&quot;timeBands&quot;: [
{
&quot;start&quot;: &quot;10:00&quot;,
&quot;end&quot;: &quot;22:00&quot;,
},
{
&quot;start&quot;: &quot;12:00&quot;,
&quot;end&quot;: &quot;20:00&quot;,
}
],
&quot;activationTypes&quot;: [ &quot;SMS&quot;,&quot;WEB&quot;,&quot;Channel&quot;],
&quot;channels&quot;: [ &quot;Hshenid&quot;,&quot;Genisis&quot;,&quot;Selfcare&quot;],
&quot;users&quot;: [ &quot;Selfcare&quot; ]
}

Changes

&quot;timeBands&quot;: [
{
&quot;start&quot;: &quot;10:00&quot;,
&quot;end&quot;: &quot;22:00&quot;,
},
{
&quot;start&quot;: &quot;12:00&quot;,
&quot;end&quot;: &quot;20:00&quot;,
}
],
&quot;activationTypes&quot;: [ &quot;SMS&quot;,&quot;WEB&quot;,&quot;Channel&quot;],
&quot;channels&quot;: [ &quot;Hshenid&quot;,&quot;Genisis&quot;,&quot;Selfcare&quot;],
&quot;users&quot;: [ &quot;Selfcare&quot; ]

Service Class Implementation

 @Override
public Optional&lt;Pack&gt; findById(int id) {
return packRepository.findById(id);
}

Model Class

@Id
@GeneratedValue(strategy= GenerationType.IDENTITY )
int packId;
String packType;
String shortCode;
String packDescription;
String startDate;
String endDate;
int validityValue;
String validityType;
Boolean expiryAction;
int expiryMsg;
int activationSMS;
Boolean deactivationAction;
String deactivationShortCode;
int deactivationSMS;
Boolean deprovisionOnExpiry;
@ManyToMany(cascade = {CascadeType.MERGE})
@JoinTable(name = &quot;PacksTimeBands&quot;,
joinColumns = @JoinColumn(name = &quot;pack_id&quot;, referencedColumnName = &quot;packId&quot;),
inverseJoinColumns = @JoinColumn(name = &quot;timeband_id&quot;, referencedColumnName = &quot;timeBandId&quot;),
uniqueConstraints = {@UniqueConstraint(columnNames = {&quot;pack_id&quot;, &quot;timeband_id&quot;})})
List&lt;TimeBand&gt; timeBands;
@ManyToMany(cascade = {CascadeType.MERGE})
@JoinTable(name = &quot;PacksActivationTypes&quot;,
joinColumns = @JoinColumn(name = &quot;pack_id&quot;, referencedColumnName = &quot;packId&quot;),
inverseJoinColumns = @JoinColumn(name = &quot;activationtype_id&quot;, referencedColumnName = &quot;activationTypeId&quot;),
uniqueConstraints = {@UniqueConstraint(columnNames = {&quot;pack_id&quot;, &quot;activationtype_id&quot;})})
List&lt;ActivationType&gt; activationTypes;
@ManyToMany(cascade = {CascadeType.MERGE})
@JoinTable(name = &quot;PacksChannels&quot;,
joinColumns = @JoinColumn(name = &quot;pack_id&quot;, referencedColumnName = &quot;packId&quot;),
inverseJoinColumns = @JoinColumn(name = &quot;channel_id&quot;, referencedColumnName = &quot;channelId&quot;),
uniqueConstraints = {@UniqueConstraint(columnNames = {&quot;pack_id&quot;, &quot;channel_id&quot;})})
List&lt;Channel&gt; channels;
@ManyToMany(cascade = {CascadeType.MERGE})
@JoinTable(name = &quot;PacksUsers&quot;,
joinColumns = @JoinColumn(name = &quot;pack_id&quot;, referencedColumnName = &quot;packId&quot;),
inverseJoinColumns = @JoinColumn(name = &quot;user_id&quot;, referencedColumnName = &quot;userId&quot;),
uniqueConstraints = {@UniqueConstraint(columnNames = {&quot;pack_id&quot;, &quot;user_id&quot;})})
List&lt;User&gt; users;

答案1

得分: 1

请注意,代码中的一些内容可能无法直接翻译成中文,因为其中涉及了一些编程术语和变量名。以下是您提供的代码的翻译部分:

另一种将您期望的响应转换的方法

public Map<String, Object> generateResponse(Optional<Pack> object){
    Map<String, Object> response = new HashMap<>();
    if(object.isPresent()){
        response.put("packId", object.get().getId());
        response.put("packType", object.get().getType());
        ..... 放入您想要的所有值
        
        // 对于要返回在列表中的对象,您可以这样做
        ArrayList<?> timeBands = new ArrayList<>();
        object.get().getTimeBands().forEach(timeBand -> {
            Map<?, ?> singleBand = new HashMap<>();
            singleBand.put("start", timeBand.getStart());
            singleBand.put("end", timeBand.getEnd()); 
            // 最后将此对象添加到列表中
            timeBands.add(singleBand);     
        });

        ArrayList<?> activationType = new ArrayList<>();
        object.get().getActivationTypes().forEach(activationTime -> {
            activationType.add(activationTime.get());
        });
        // 将您要保留的时间段的键放入最终响应映射
        response.put("您想要为timeBands保留的键", timeBands);
        response.put("您想要为activationType保留的键", activationType);

        return response;
    }
}

对于列表类型的参数

public List<?> generateResponse(List<Pack> object){
    ArrayList<?> formattedListPacks = new ArrayList<>();
    
    object.forEach(pack -> {
        Map<String, Object> response = new HashMap<>();
        response.put("packId", pack.getId());
        response.put("packType", pack.getType());
        ..... 放入您想要的所有值
        
        // 对于要返回在列表中的对象,您可以这样做
        ArrayList<?> timeBands = new ArrayList<>();
        pack.getTimeBands().forEach(timeBand -> {
            Map<?, ?> singleBand = new HashMap<>();
            singleBand.put("start", timeBand.getStart());
            singleBand.put("end", timeBand.getEnd()); 
            // 最后将此对象添加到列表中
            timeBands.add(singleBand);     
        });

        ArrayList<?> activationType = new ArrayList<>();
        pack.getTimeBands().forEach(activationTime -> {
            activationType.add(activationTime.get());
        });
        // 将您要保留的时间段的键放入最终响应映射
        response.put("您想要为timeBands保留的键", timeBands);
        response.put("您想要为activationType保留的键", activationType);

        formattedListPacks.add(response);
    });
    return formattedListPacks;
}
英文:

Like so,

 Optional&lt;Pack&gt; findById(Long id);

Another Method to convert your expected response.

public Map&lt;String, Objects&gt; generateResponse(Optional&lt;Pack&gt; object){
Map&lt;String, Object&gt; response = new HashMap&lt;&gt;();
if(object.isPresent()){
response.put(&quot;packId&quot;, object.get().getid());
response.put(&quot;packType&quot;, object.get().getType());
..... put all the values that you want
//For Objects you want to return in list you can do that this way
ArrayList&lt;?&gt; timeBands = new ArrayList&lt;&gt;();
object.get().timeBands().forEach(timeBand -&gt;{
Map&lt;?&gt; singleBand = new HashMap&lt;&gt;();
singleBand.put(&quot;start&quot;, timeBand.getStart());
singleBand.put(&quot;end&quot;, timeBand.getEnd()); 
//Finally add this Object in list
timeBands.add(singleBand);     
});
ArrayList&lt;?&gt; activationType = new ArrayList&lt;&gt;();
object.get().timeBands().forEach(activationTypes -&gt;{
activationType.add(activationTime.get())
});
//Your arraylist to the final response Map
response.put(&quot;key you want to keep for timeBands&quot;, timeBands);
response.put(&quot;key you want to keep for activationType&quot;, 
activationType);
return response;
}
}

For list type argument

public List&lt;?&gt; generateResponse(List&lt;Pack&gt; object){
ArrayList&lt;?&gt; formattedListPacks = new ArrayList&lt;&gt;();
object.forEach( pack -&gt;{
Map&lt;String, Object&gt; response = new HashMap&lt;&gt;();
response.put(&quot;packId&quot;, object.get().getid());
response.put(&quot;packType&quot;, object.get().getType());
..... put all the values that you want
//For Objects you want to return in list you can do that this way
ArrayList&lt;?&gt; timeBands = new ArrayList&lt;&gt;();
object.get().timeBands().forEach(timeBand -&gt;{
Map&lt;?&gt; singleBand = new HashMap&lt;&gt;();
singleBand.put(&quot;start&quot;, timeBand.getStart());
singleBand.put(&quot;end&quot;, timeBand.getEnd()); 
//Finally add this Object in list
timeBands.add(singleBand);     
});
ArrayList&lt;?&gt; activationType = new ArrayList&lt;&gt;();
object.get().timeBands().forEach(activationTypes -&gt;{
activationType.add(activationTime.get())
});
//Your arraylist to the final response Map
response.put(&quot;key you want to keep for timeBands&quot;, timeBands);
response.put(&quot;key you want to keep for activationType&quot;, 
activationType);
formattedListPacks.add(response);
});
return formattedListPacks;
}

huangapple
  • 本文由 发表于 2020年8月25日 12:33:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63572089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定