簡體   English   中英

澤西島-JSON僅封送特定字段

[英]Jersey - JSON marshall only specific fields

我的REST服務返回以下JSON

{
  "name": "John",
  "id" : 10
}

我可以使用Jersey將其編組為以下Bean:

public class User{
    private String name;
    //getter & setter
}

我想用下面的代碼做到這一點,但它不起作用

WebResource webResource = client.resource(url);
webResource.accept(MediaType.APPLICATION_JSON_TYPE);
User user = webResource.get(User.class);

這是否有可能,或者我必須在Java Bean中實現完整的JSON結構才能使其正常工作?

我知道我可以使用Jackson和其他任何方法來解析此JSON。

使用Jackson,最簡單的方法是像這樣配置ObjectMapper:

 objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, 
false);

檢查這個樣本提供者

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;
   }
}

使用Jackson:您有兩種選擇:

  1. 傑克遜致力於田野工匠。 因此,您只需刪除要在JSON中省略的字段的getter。 (如果您不需要其他地方的吸氣劑。)

  2. 或者,您可以在該字段的getter方法上使用Jackson@JsonIgnore 批注,並且在結果JSON中看不到這樣的鍵值對。

     @JsonIgnore public int getSecurityCode(){ return securityCode; } 

在您的bean中,在類級別添加注釋@JsonIgnoreProperties(ignoreUnknown = true) ,並且它應該跳過JSON中的id屬性,因為它不存在於bean中。

@JsonIgnoreProperties(ignoreUnknown = true)
public class User{
    private String name;
    //getter & setter
}

(有關詳細信息,請參見http://wiki.fasterxml.com/JacksonAnnotations

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM