[英]Mapping Dynamic Json response(has changing attributes) using Jackson
I am trying to map Json response whose attributes changes if there is any error.我正在尝试 map Json 响应,如果出现任何错误,其属性会发生变化。 For example:
例如:
valid response:有效回复:
{
"Header":[{
//some data
}],
"Component":[{
//data
}],
"ServiceParameter":[{
//data
}]
}
error response:错误响应:
{
"Header":[{
//some data
}],
"ErrorMessage":[{
//data
}],
"ServiceParameter":[{
//data
}]
}
How can I map(with Jackson if possible) component data or error message for the given response?如何为给定的响应映射(如果可能,使用 Jackson)组件数据或错误消息?
I can only think of having both fields included in your POJO, like this:我只能想到将这两个字段都包含在您的 POJO 中,如下所示:
class JsonResponse {
@JsonProperty("Headers")
private List<Header> headers;
@JsonProperty("Component")
private List<Component> components;
@JsonProperty("ErrorMessage")
private List<ErrorMessages> errorMessages;
@JsonProperty("ServiceParameters")
private List<ServiceParameters> serviceParameters;
// Getters and setters
}
You can then know whether it's an error or not by checking if the errorMessages list is empty or not.然后,您可以通过检查 errorMessages 列表是否为空来知道它是否是错误。
Jackson is a very flexible JSON (de)serializer, so it's very likely there's a way to do it, but this one is definitely the easiest one! Jackson 是一款非常灵活的 JSON (de)serializer,所以很有可能有办法做到这一点,但这个绝对是最简单的一个!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.