java - 避免在 Jackson 中运行时序列化某些字段

标签 java json spring-boot jackson

我有一个生成 JSON 的 Controller ,从该 Controller 中,我返回一个实体对象,该对象由 Jackson 自动序列化。

现在,我想避免根据传递给 Controller ​​的参数返回一些字段。我查看了使用 FilterProperties/Mixins 等完成此操作的示例。但是我看到的所有示例都要求我使用 ObjectMapper 手动序列化/反序列化 bean。有没有什么方法可以在不手动序列化的情况下做到这一点?我的代码与此类似:

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

现在,根据传递给 Controller ​​的“变量”的值,我想显示/隐藏 MyEntity 的 col2。我不想手动序列化/反序列化该类。有什么办法可以做到这一点吗?我可以从外部更改 Mapper Jackson 用于根据“变量”的值序列化类吗?

最佳答案

使用JsonViewMappingJacksonValue 结合使用.

考虑以下示例:

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

然后在 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;
}

关于java - 避免在 Jackson 中运行时序列化某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903846/

相关文章:

java - UnitTest call/swagger-ui.html 导致 springdoc-openapi 出现 404

Java - 使用 linux 访问远程 Activity 目录

java - 在java中输入有效的时间格式

javascript - 在 Polymer 中使用 iron-ajax 接收错误 "Polymer::Attributes: couldn' t 将数组解码为 JSON"

java - Jersey 休息 : how to return interface instead of class

java - 在 Maven 依赖项中重写时重写 Spring Security 配置(HttpSecurity)

java - Spring Boot 无法正确渲染 View

java.net.URI - : Illegal character in fragment at index XXX - due to character "#"

Java 泛型。类型不匹配 : cannot convert from object to

ios - 如何检查 NSDictionary 键值是否为空?