BAEL-7765: How to fix JsonParseException: Unexpected character (code 115) when parsing unquoted JSON in Jackson (#16286)

This commit is contained in:
ACHRAF TAITAI 2024-04-04 18:00:20 +02:00 committed by GitHub
parent d21e80d93d
commit 37eb20833e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 17 additions and 11 deletions

View File

@ -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'}";