baeldung-articles : BAEL-7644 (#16211)

* baeldung-articles : BAEL-7644

Include null value in JSON serialization (Main)

* baeldung-articles : BAEL-7644

Include null value in JSON serialization (Test).
This commit is contained in:
DiegoMarti2 2024-03-26 00:07:55 +02:00 committed by GitHub
parent c75b4b13fa
commit 4435123918
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,27 @@
package com.baeldung.includenullinjson;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Customer {
@JsonProperty
private final String name;
@JsonProperty
private final String address;
@JsonProperty
private final int age;
public Customer(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
@Override
public String toString() {
return "Customer{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.includenullinjson;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class IncludeNullValuesInJsonUnitTest {
String expectedJson = "{\"name\":\"John\",\"address\":null,\"age\":25}";
Customer obj = new Customer("John", null, 25);
@Test
public void givenObjectWithNullField_whenJacksonUsed_thenIncludesNullValue() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
String json = mapper.writeValueAsString(obj);
assertEquals(expectedJson, json);
}
@Test
public void givenObjectWithNullField_whenGsonUsed_thenIncludesNullValue() {
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(obj);
assertEquals(expectedJson, json);
}
}