From 37eb20833e56c7c419c3e37db3acec19fd389d24 Mon Sep 17 00:00:00 2001 From: ACHRAF TAITAI <43656331+achraftt@users.noreply.github.com> Date: Thu, 4 Apr 2024 18:00:20 +0200 Subject: [PATCH] BAEL-7765: How to fix JsonParseException: Unexpected character (code 115) when parsing unquoted JSON in Jackson (#16286) --- .../exceptions/JacksonExceptionsUnitTest.java | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java index 127d466436..e1517ed09b 100644 --- a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java +++ b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java @@ -1,16 +1,5 @@ package com.baeldung.exceptions; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.List; - -import org.junit.Test; - import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonFactory; @@ -22,6 +11,13 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.*; public class JacksonExceptionsUnitTest { @@ -201,6 +197,16 @@ public class JacksonExceptionsUnitTest { .readValue(json); } + // JsonParseException: Unexpected character ('n' (code 110)) + @Test(expected = JsonParseException.class) + public void givenInvalidJsonString_whenDeserializing_thenException() throws JsonProcessingException, IOException { + final String json = "{\"id\":1, name:\"John\"}"; // Missing double quotes around 'name' + final ObjectMapper mapper = new ObjectMapper(); + mapper.reader() + .forType(User.class) + .readValue(json); + } + @Test public void givenStringWithSingleQuotes_whenConfigureDeserializing_thenCorrect() throws JsonProcessingException, IOException { final String json = "{'id':1,'name':'John'}";