[英]Processing JSON response using JAX-RS
I have a json payload like this:
{
"account": {
"sample_id": 1424876658095,
"parameters": [
{
"name": "email",
"value": "hello@xyz.com"
},
{
"name": "first_name",
"value": "FIRSTNAME"
},
{
"name": "last_name",
"value": "LASTNAME"
}
]
},
"assests": [ {
"tran_id": "1234567",
}]
}
The above json payload is getting generated in the response of a rest API call. 上面的json有效负载是在rest API调用的响应中生成的。 I would like to process this response in java to generate something like this:
我想在Java中处理此响应以生成如下内容:
{
"account": {
"sample_id": 1424876658095,
"email_id": "hello@xyz.com",
"first_name": "FIRSTNAME",
"last_name": "LASTNAME",
},
"assets": [ {
"tran_id": "1234567",
}]
}
I am using the JAX-RS specification for the REST API, but I am not able to find any library to process the response. 我正在使用REST API的JAX-RS规范,但找不到任何库来处理响应。
If you want to leverage the Jackson serialization within JAX-Rs, you need to implement as custom serializer. 如果要在JAX-R中利用Jackson序列化,则需要实现为自定义序列化器。
There are two steps to do that: 有两个步骤可以做到这一点:
Create the custom serializer 创建自定义序列化器
Here is a sample of a custom Jackson serializer for your needs based on beans AccountBean
and ParameterBean
: 这是一个基于bean
AccountBean
和ParameterBean
的自定义Jackson序列化器的示例,可满足您的需求:
public class AccountBeanSerializer extends JsonSerializer<AccountBean> { @Override public void serialize(AccountBean accountBean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeNumberField("sample_id", accountBean.getSampleId()); List<ParameterBean> parameters = accountBean.getParameters(); for (ParameterBean parameterBean : parameters) { jgen.writeStringField(parameterBean.getName(), parameterBean.getValue()); } jgen.writeEndObject(); } }
I assume the class for your response if something like that: 如果出现类似这样的情况,我认为是您的回答:
class ResponseBean field account = class AccountBean field sampleId (long) field parameters = class ParameterBean (...)
Register the custom serializer 注册自定义序列化器
You need then to provide a custom Jackson configuration within a context resolver. 然后,您需要在上下文解析器中提供自定义的Jackson配置。 For this, you can create an implementation of the interface
ContextResolver
annotated with Provider
. 为此,您可以创建带有
Provider
注释的ContextResolver
接口的实现。
@Provider public class CustomJacksonConfig implements ContextResolver<ObjectMapper> { private ObjectMapper objectMapper; public JacksonConfig() { this.objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null)); module.addSerializer(AccountBean.class, new AccountSerializer()); this.objectMapper.registerModule(module); } public ObjectMapper getContext(Class<?> objectType) { return objectMapper; } }
Following links could help you: 以下链接可以为您提供帮助:
Hope this helps, Thierry 希望这会有所帮助,蒂埃里
为此,您将必须实现一个自定义MessageBodyWriter
才能为您的POJO生成不同于默认值的JSON负载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.