英文:
Change JSON value from null to empty String
问题
我正在创建一个返回 JSON 的 REST 控制器。我从数据库中获取这些数据,然后映射到一个 Java 类,使用 setter 和 getter 方法。
{
"example": null,
"this": null,
"is": null,
"only": null,
"example": null,
"foo": null,
"bar": null,
"blabla": null,
"lala": null
}
这是因为数据库中没有数据。但我希望数据像这样:
{
"example": "",
"this": "",
"is": "",
"only": "",
"example": "",
"foo": "",
"bar": "",
"blabla": "",
"lala": ""
}
我有超过100个字段,所以我认为在每个变量中使用 if-else 不是一个好方法。
英文:
im making a rest controller which return json. i get this data from database, mapping in to java class using setter getter.
{
"example": null,
"this": null,
"is": null,
"only": null,
"example": null,
"foo": null,
"bar": null,
"blabla": null,
"lala": null
}
its because the data in database not present. but i want the data to be like this:
{
"example": "" ,
"this": "",
"is": "",
"only": "",
"example": "",
"foo": "",
"bar": "",
"blabla": "",
"lala": ""
}
i have more than 100 fields. so i think its not good to use if else in every variable.
答案1
得分: 2
可以覆盖默认的 ObjectMapper
(由Spring Boot自动配置提供),并全局配置用于类型为 String
的属性的格式。
@Configuration
public class JacksonConfiguration {
@Bean
ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
final var objectMapper = builder.createXmlMapper(false).build();
objectMapper.configOverride(String.class).setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));
return objectMapper;
}
}
英文:
You can override default ObjectMapper
(provided by Spring Boot auto-configuration) and configure globally format to use for properties of type String
.
@Configuration
public class JacksonConfiguration {
@Bean
ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
final var objectMapper = builder.createXmlMapper(false).build();
objectMapper.configOverride(String.class).setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));
return objectMapper;
}
}
答案2
得分: 0
DefaultSerializerProvider.Impl sp = new DefaultSerializerProvider.Impl();
sp.setNullValueSerializer(new NullSerializer());
new ObjectMapper().setSerializerProvider(sp)...
Where
public class NullSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
}
英文:
DefaultSerializerProvider.Impl sp = new DefaultSerializerProvider.Impl();
sp.setNullValueSerializer(new NullSerializer());
new ObjectMapper().setSerializerProvider(sp)...
Where
public class NullSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
}
答案3
得分: 0
你可以通过处理 JSON 字符串来更轻松地解决它:
jsonString = jsonString.replaceAll("null,", "''");
英文:
You can solve it more easily by handling json string:
jsonString = jsonString.replaceAll("null,", "'',");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论