如何使用Micronaut启用JsonView

时间:2019-04-18 14:12:12

标签: java jackson lombok micronaut json-view

关于这个问题,我已经获得了Micronaut的最新版本(1.1.0),并且看到已经添加了对@JsonView jackson批注的支持。但是,当我将其添加到控制器并在application.yml中启用它时,看不到将注释应用于响应,我仍然收到完整的对象。注意:我在POJO上也使用了Lombok,我不知道这是否会造成干扰。

控制器:

@Controller("/v1")
public class Controller {

private MongoClient client;

public Controller(MongoClient mongoClient) {
    this.client = mongoClient;
}

@Get("/ids")
@Produces(MediaType.APPLICATION_JSON)
@JsonView(Views.IdOnly.class)
public Single<List<Grain>> getIdsByClientId(@QueryValue(value = "clientId") String clientId) {
    return Flowable.fromPublisher(getCollection().find(Filters.eq("data.clientId", clientId))).toList();
}

private MongoCollection<Grain> getCollection() {
    CodecRegistry grainRegistry = CodecRegistries.fromRegistries(MongoClients.getDefaultCodecRegistry(), CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    return client
            .getDatabase("db").withCodecRegistry(grainRegistry)
            .getCollection("col", Data.class);
}

}

数据:

@Data
@NoArgsConstructor
public class Data {

    @JsonSerialize(using = ToStringSerializer.class)
    @JsonView(Views.IdOnly.class)
    private ObjectId id;

    private boolean active = true;

    @Valid
    @NotNull
    private DataMeta dataMeta;

    @Valid
    @NotNull
    private DataContent dataContent;

}

查看:

public class Views {

    public static class IdOnly {
    }
}

application.yml

---
micronaut:
  application:
    name: mojave-query-api

---
mongodb:
  uri: "mongodb://${MONGO_USER:user}:${MONGO_PASSWORD:password}@${MONGO_HOST:localhost}:${MONGO_PORT:27017}/db?ssl=false&authSource=db"

---
jackson.json-view.enabled: true

application.yml(替代版本也不起作用)

---
micronaut:
  application:
    name: mojave-query-api

---
mongodb:
  uri: "mongodb://${MONGO_USER:user}:${MONGO_PASSWORD:password}@${MONGO_HOST:localhost}:${MONGO_PORT:27017}/db?ssl=false&authSource=db"

---
jackson:
  json-view:
    enabled: true

我不确定是否在application.yml文件中的错误位置放置了杰克逊线,或者该功能是否无法正常使用,或者我完全缺失了某些东西?输入表示赞赏!

1 个答案:

答案 0 :(得分:1)

最新版本的application.yml是正确的,但是您忘记将Data类标记为@JsonView类,因此工作版本为


@Data
@JsonView
@NoArgsConstructor
public class Data {

    @JsonSerialize(using = ToStringSerializer.class)
    @JsonView(Views.IdOnly.class)
    private ObjectId id;

    private boolean active = true;

    @Valid
    @NotNull
    private DataMeta dataMeta;

    @Valid
    @NotNull
    private DataContent dataContent;

}