[BAEL-5780] Difference Between asText() and toString() in JsonNode (#13601)

* [BAEL-5780] Difference Between asText() and toString() in JsonNode

* chore: add test to demonstrate the difference at the special chars aspect

* fix: follow tests names convention

* fix: follow tests names convention
This commit is contained in:
Almog Tavor 2023-03-22 04:07:56 +02:00 committed by GitHub
parent ca107bcc9f
commit 5fdce22ac5
1 changed files with 53 additions and 0 deletions

View File

@ -0,0 +1,53 @@
package com.baeldung.jackson.jsonnode;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
class AsTextVsAsStringUnitTest {
@Test
void shouldUseAsText() throws JsonProcessingException {
String json = "{\"name\":\"John\",\"age\":30}";
JsonNode node = new ObjectMapper().readTree(json);
String name = node.get("name")
.asText();
String age = node.get("age")
.asText();
String jsonText = node.asText();
assertThat(jsonText).isEmpty();
assertThat(name).isEqualTo("John");
assertThat(age).isEqualTo("30");
}
@Test
void shouldUseAsTextWithEscapeCharacters() throws JsonProcessingException {
String specialCharsJson = "{\"text\":\"Hello \\\"world\\\" !\"}";
JsonNode specialCharsNode = new ObjectMapper().readTree(specialCharsJson);
String specialCharsJsonAsText = specialCharsNode.get("text")
.asText();
String specialCharsJsonToString = specialCharsNode.get("text")
.toString();
assertThat(specialCharsJsonAsText).isEqualTo("Hello \"world\" !");
assertThat(specialCharsJsonToString).isEqualTo("\"Hello \\\"world\\\" !\"");
}
@Test
void shouldUseToString() throws JsonProcessingException {
String json = "{\"name\":\"John\",\"age\":30}";
JsonNode node = new ObjectMapper().readTree(json);
String jsonString = node.toString();
String name = node.get("name")
.toString();
String age = node.get("age")
.toString();
assertThat(jsonString).isEqualTo("{\"name\":\"John\",\"age\":30}");
assertThat(name).isEqualTo("\"John\"");
assertThat(age).isEqualTo("30");
}
}