[英]Jersey - JSON marshall only specific fields
My REST service returns following JSON 我的REST服务返回以下JSON
{
"name": "John",
"id" : 10
}
Can I use Jersey to marshall it into following Bean: 我可以使用Jersey将其编组为以下Bean:
public class User{
private String name;
//getter & setter
}
I wanted to do this with following code but it doesn't work 我想用下面的代码做到这一点,但它不起作用
WebResource webResource = client.resource(url);
webResource.accept(MediaType.APPLICATION_JSON_TYPE);
User user = webResource.get(User.class);
Is this even possible or I have to implement full JSON structure in Java Beans to get it work? 这是否有可能,或者我必须在Java Bean中实现完整的JSON结构才能使其正常工作?
I know that I can parse this JSON with Jackson and any other methods. 我知道我可以使用Jackson和其他任何方法来解析此JSON。
With Jackson, easiest way is to configure ObjectMapper like so: 使用Jackson,最简单的方法是像这样配置ObjectMapper:
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
Check this sample provider 检查这个样本提供者
package com.company.rest.jersey;
@Provider
@Component
@Produces({MediaType.APPLICATION_JSON})
public class JacksonMapperProvider implements ContextResolver<ObjectMapper> {
ObjectMapper mapper;
public JacksonMapperProvider(){
mapper = new ObjectMapper();
mapper.configure(Feature.INDENT_OUTPUT, true);
// Serialize dates using ISO8601 format
// Jackson uses timestamps by default, so use StdDateFormat to get ISO8601
mapper.getSerializationConfig().setDateFormat(new StdDateFormat());
// Deserialize dates using ISO8601 format
// MilliDateFormat simply adds milliseconds to string if missing so it will parse
mapper.getDeserializationConfig().setDateFormat(new MilliDateFormat());
// Prevent exceptions from being thrown for unknown properties
mapper.configure(
DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
}
@Override
public ObjectMapper getContext(Class<?> aClass) {
return mapper;
}
}
With Jackson : You have two options: 使用Jackson:您有两种选择:
Jackson works on setters-getters of fields. 杰克逊致力于田野工匠。 So, you can just remove getter of field which you want to omit in JSON.
因此,您只需删除要在JSON中省略的字段的getter。 ( If you don't need getter at other place.)
(如果您不需要其他地方的吸气剂。)
Or, you can use the @JsonIgnore
annotation of Jackson on getter method of that field and you see there in no such key-value pair in resulted JSON. 或者,您可以在该字段的getter方法上使用Jackson的
@JsonIgnore
批注,并且在结果JSON中看不到这样的键值对。
@JsonIgnore public int getSecurityCode(){ return securityCode; }
In your bean, add the annotation @JsonIgnoreProperties(ignoreUnknown = true)
at the class level and it should skip the id property in the JSON since it's not present in the bean. 在您的bean中,在类级别添加注释
@JsonIgnoreProperties(ignoreUnknown = true)
,并且它应该跳过JSON中的id属性,因为它不存在于bean中。
@JsonIgnoreProperties(ignoreUnknown = true)
public class User{
private String name;
//getter & setter
}
(See http://wiki.fasterxml.com/JacksonAnnotations for details) (有关详细信息,请参见http://wiki.fasterxml.com/JacksonAnnotations )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.