如何在REST API Java中忽略响应中的特定字段

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

How to ignore certain field from response in REST API Java

问题

Microservice A调用Microservice B并将响应返回给Microservice A。要求非常简单,验证信用卡号并在响应中返回成功或失败。请查看我的代码:

Microservice A:

@RestController
public class TestController {

    @PostMapping("/users")
    public CreditCard createUser(@RequestBody CreditCard creditCard) {

        Map<String, String> ccDetails = new HashMap<>();
        ccDetails.put("ccNumber", creditCard.getCcNumber());

        ResponseEntity<CreditCard> responseEntity = new RestTemplate()
                .getForEntity("http://localhost:8081/validation/cc/{ccNumber}", CreditCard.class, ccDetails);

        return responseEntity.getBody();
    }
}

CreditCard.java

public class CreditCard {

    private String status;
    private String ccNumber;

    public CreditCard() {
    }

    public String getStatus() {
        return status;
    }
    public String getCcNumber() {
        return ccNumber;
    }
    public void setCcNumber(String ccNumber) {
        this.ccNumber = ccNumber;
    }
}

Microservice B:

ValidateCCResource.java

@RestController
@RequestMapping("/validation")
public class ValidateCCResource {

    @GetMapping("/cc/{ccNumber}")
    public CreditCardValidation validateCreditCardApplication(@PathVariable String ccNumber) {

        CreditCardValidation response = new CreditCardValidation();
        if (ccNumber.length() == 16) {
            System.out.println("valid credit card - success");
            response.setStatus("Credit Card Number is Valid");
        } else {
            response.setStatus("Credit Card Number is Not Valid");
        }
        return response;
    }
}

CreditCardValidation.java

public class CreditCardValidation {

    private String status;

    public CreditCardValidation() {
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }
}

请求体:

{
    "ccNumber": "1234432232232233"
}

实际响应:

{
    "status": "Credit Card Number is Valid",
    "ccNumber": null
}

期望响应:

{
    "status": "Credit Card Number is Valid"
}

我想忽略响应中的ccNumber,我尝试使用@JsonIgnore,但它不起作用 - 请问有人可以帮助我如何从响应中去掉ccNumber。

英文:

I've written two microservices, Microservice A is calling Microservice B and returning the response to Microservice A. The requirement is very simple to validate the credit card number and return success or failure in the response. Please find my code below:

Microservice A:

@RestController
public class TestController {

	@PostMapping(&quot;/users&quot;)
	public CreditCard createUser(@RequestBody CreditCard creditCard) {

		Map&lt;String, String&gt; ccDetails = new HashMap&lt;&gt;();
		ccDetails.put(&quot;ccNumber&quot;, creditCard.getCcNumber());

		ResponseEntity&lt;CreditCard&gt; responseEntity = new RestTemplate()
				.getForEntity(&quot;http://localhost:8081/validation/cc/{ccNumber}&quot;, CreditCard.class, ccDetails);

		return responseEntity.getBody();
	}
}

CreditCard.java

public class CreditCard {

	private String status;
	private String ccNumber;

	public CreditCard() {
	}

	public String getStatus() {
		return status;
	}
	public String getCcNumber() {
		return ccNumber;
	}
	public void setCcNumber(String ccNumber) {
		this.ccNumber = ccNumber;
	}

}

Microservice B:

ValidateCCResource.java

@RestController
@RequestMapping(&quot;/validation&quot;)
public class ValidateCCResource {

	@GetMapping(&quot;/cc/{ccNumber}&quot;)
	public CreditCardValidation validateCreditCardApplication(@PathVariable String ccNumber) {

		CreditCardValidation response = new CreditCardValidation();
		if (ccNumber.length() == 16) {
			System.out.println(&quot;valid credit card - success&quot;);
			response.setStatus(&quot;Credit Card Number is Valid&quot;);
		} else {
			response.setStatus(&quot;Credit Card Number is Not Valid&quot;);
		}
		return response;
	}
}

CreditCardValidation.java

public class CreditCardValidation {

	private String status;

	public CreditCardValidation() {
	}

public void setStatus(String status) {
	this.status = status;
}

	public String getStatus() {
		return status;
	}
}

Request Body:

{
    &quot;ccNumber&quot;: &quot;1234432232232233&quot;
}

Actual Response:

{
    &quot;status&quot;: &quot;Credit Card Number is Valid&quot;,
    &quot;ccNumber&quot;: null
}

Expected Response:

{
    &quot;status&quot;: &quot;Credit Card Number is Valid&quot;
}

I would like to ignore ccNumber in the response, I tried using @JsonIgnore but its not working- can someone please help how to get rid of the ccNumber from my response.

答案1

得分: 2

如果我理解你的问题正确,这是你可以做的事情:

  1. 如果你不想包括null对象作为响应的一部分,那么你可以在你的模型/数据/DTO类的属性上使用@JsonInclude(Include.NON_NULL)注解。

  2. 如果你不想包括任何特定字段,你可以在模型/数据/DTO类中的该属性上使用@Transient注解。

它是如何工作的:

因此,当将模型/数据/DTO类从对象转换为JSON时,所有这些类都会被序列化。在进行此序列化时,你可以决定自定义逻辑来确定最终的JSON响应是什么样的。
这是通过Java中提供的可用注解(以及你用于序列化的任何库)来实现的。

英文:

If I get your question correctly, here is what you can do :-

  1. If you don't want to include null objects to be part of your response, then you can use @JsonInclude(Include.NON_NULL) annotation on the property of you model/data/dto class.

  2. If you want not to include any specific field at all, then you can annotate that property with @Transient in the model/data/dto class.

How's it working:

So, all your model/data/dto classes get serialized when they are converted into JSON from Object. While this serialization takes place, you can decide your customized logic to determine what the final JSON response would be.
This is achieved simply by the available annotations in Java (and or whatever library you are using for Serialization).

huangapple
  • 本文由 发表于 2020年8月10日 11:20:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63333682.html
匿名

发表评论

匿名网友

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

确定