1

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.

3
  • How are you deserializing the json? Can you add that logic there? Commented Sep 22, 2020 at 8:26
  • Lookup this answer stackoverflow.com/questions/38071243/… Commented Sep 22, 2020 at 11:40
  • @TomerShetah im using ObjectMapper.valueToTree, it still get null. im using class and then return to controller still get null too. Commented Sep 22, 2020 at 12:58

3 Answers 3

2

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

}
Sign up to request clarification or add additional context in comments.

5 Comments

is var in java8 equals object?
var can be used in a local variable declaration instead of the variable's type. It's available since Java 10. Java 8 equivalent syntax is - final ObjectMapper objectMapper = ...
it still get null if the data in db not present.
make sure you injected ObjectMapper configured by Spring into your controller.
@Autowired private ObjectMapper mapper; and then JsonNode tes = mapper.valueToTree(result); still get null
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("");
    }
}

Comments

0

You can solve it more easily by handling json string:

jsonString = jsonString.replaceAll("null,", "'',");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.