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:
parent
c75b4b13fa
commit
4435123918
|
@ -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 +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue