英文:
How to provide default value as "true" to a boolean field jackson property
问题
我正在使用Jackson API的**@JsonProperty注解来创建一个模型,我需要将一个布尔属性的默认值设置为true**(默认为false)。@JsonProperty的defaultValue属性只接受字符串。有人可以建议一下,我如何将布尔模型属性的默认值设置为true。
我已经尝试了以下方法,但并不起作用:
@JsonProperty(value = "field1", required = false)
@ApiObjectField(name = "field1", description = "field1")
private boolean field1 = true;
// 获取器和设置器
英文:
I am using jackson api @JsonProperty annotation for creating a model and i need to give default value as true to a boolean property(by default it is false). The defaultValue attribute of @JsonProperty only takes string. Can anybody suggest how can i provide default value as true to a boolean model property
I have tried the following way, but it doesnt work
@JsonProperty(value = "field1", required = false)
@ApiObjectField(name = "field1", description = "field1")
private boolean field1 = true;
//getters and setters
答案1
得分: 4
以下代码应该可以工作:
@JsonProperty(value = "required")
private boolean required = true;
英文:
Below code should work
@JsonProperty(value = "required")
private boolean required = true;
答案2
得分: 0
创建一个带有 @JsonCreator
注解的构造函数,该构造函数接收您想要设置为对象的所有 JSON 属性,并为具有空值的任何输入字段设置默认值。
@JsonCreator
MyObject(@JsonProperty("field1") Boolean field1) {
this.field1 = field1 == null ? true : field1;
}
免责声明:我尚未测试上述代码。
英文:
Create a constructor annotated with the @JsonCreator
that receives all json properties you want to set to your object, and set a default value to whatever input field that has a null value.
@JsonCreator
MyObject(@JsonProperty("field1") Boolean field1) {
this.field1 = field1 == null ? true : field1;
}
Disclaimer: I haven't tested the code above.
答案3
得分: 0
创建一个自定义序列化器,然后将其添加:
@JsonSerialize(using = MyCustomSerializer.class)
private boolean field1;
编写类似以下的扩展:
public class MyCustomSerializer extends StdSerializer<Object> {
public MyCustomSerializer() {
super(Object.class);
}
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
//...
}
}
英文:
Create a custom Serialize, then add it :
@JsonSerialize(using = MyCustomSerializer.class)
private boolean field1;
Write the extension similar to:
public class MyCustomSerializer extends StdSerializer<Object> {
public MyCustomSerializer() {
super(Object.class);
}
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
//...
}
}
答案4
得分: 0
你也可以在字段的获取方法中实现这个。
就像这样:
public Boolean getField1() {
this.field1 = field1 == null ? true : field1;
return field1;
}
英文:
you can do this in field getter too.
like:
public Boolean getField1() {
this.field1 = field1 == null ? true : field1;
return field1;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论