0

我有一个pojo

@JsonIgnoreProperties(ignoreUnknown = true)
public class Item
{
   String name;

   Long baseId;

   @JsonIgnore
   String status;
}

我将这个 Java 对象用于GETPOSTPUT api 调用。我使用了@JsonIgnore注释来避免序列化(所以它不会为PUTPOST请求序列化,但我得到了GET请求)。现在我需要 baseId 应该为POST请求序列化,而不是为PUT请求序列化。请建议我解决方案。

4

1 回答 1

0

You can consider using the Jackson Json views. Basically, you replace the @JsonIgnore annotation on the Jackson view annotation with a view type and enable it depending on the context. Here is an example for a plain object mapper:

public class JacksonView {

    public static interface View1 {
    }

    public static interface View2 {
    }

    public static class Bean {
        @JsonView(View1.class)
        public final String field1;
        @JsonView(View2.class)
        public final String field2;
        public final String field3;

        public Bean(String field1, String field2, String field3) {
            this.field1 = field1;
            this.field2 = field2;
            this.field3 = field3;
        }
    }
    public static void main(String[] args) throws JsonProcessingException {
        Bean bean = new Bean("a", "b", "c");
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper
                .writer()
                .withView(View2.class)
                .writeValueAsString(bean));

    }

}

Output:

{"field2":"b","field3":"c"}

To make it work in JAX-RS you should enable the specific view by annotating your HTTP method resources as described here. Example:

@GET
@JsonView(View1.class)
public Bean doGet() {...}

@POST
@JsonView(View2.class)
public void doPost(Bean bean) {...}
于 2014-06-27T12:56:17.477 回答