简体   繁体   中英

Avoid serialization of certain fields at runtime in Jackson

I have a controller which produces JSON, and from this controller, I return an entity object, which is automatically serialized by Jackson.

Now, I want to avoid returning some fields based on a parameter passed to the controller. I looked at examples where this is done using FilterProperties / Mixins etc. But all the examples I saw requires me to use ObjectMapper to serialize / de-serialize the bean manually. Is there any way to do this without manual serialization? The code I have is similar to this:

@RestController
@RequestMapping(value = "/myapi", produces = MediaType.APPLICATION_JSON_VALUE)
public class MyController {
    @Autowired
    private MyService myService;

    @RequestMapping(value = "/test/{variable}",method=RequestMethod.GET)
    public MyEntity getMyEntity(@PathVariable("variable") String variable){
        return myservice.getEntity(variable);
    }
}

@Service("myservice")
public class MyService {
    @Autowired
    private MyEntityRepository myEntityRepository;

    public MyEntity getEntity(String variable){
        return myEntityRepository.findOne(1L);
    }
}


@Entity  
@Table(name="my_table")
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyEntity implements Serializable {

    @Column(name="col_1")
    @JsonProperty("col_1")
    private String col1;

    @Column(name="col_2")
    @JsonProperty("col_2")
    private String col2;

    // getter and setters
}

Now, based on the value of "variable" passed to the controller, I want to show/hide col2 of MyEntity. And I do not want to serialize/deserialize the class manually. Is there any way to do this? Can I externally change the Mapper Jackson uses to serialize the class based on the value of "variable"?

Use JsonView in conjunction with MappingJacksonValue .

Consider following example:

class Person {
    public static class Full {
    }

    public static class OnlyName {
    }

    @JsonView({OnlyName.class, Full.class})
    private String name;

    @JsonView(Full.class)
    private int age;

    // constructor, getters ...
}

and then in Spring MVC controller:

@RequestMapping("/")
MappingJacksonValue person(@RequestParam String view) {
    MappingJacksonValue value = new MappingJacksonValue(new Person("John Doe", 44));
    value.setSerializationView("onlyName".equals(view) ? Person.OnlyName.class : Person.Full.class);
    return value;
}

使用此注释并将值设置为null,它将不会被序列化:

@JsonInclude(Include.NON_NULL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM