Jackson MismatchedInputException (no String-argument constructor/factory method to deserialize from String value)
20:16 12 Jul 2021

I am using SpringBoot 2.3.1-RELEASE and am trying to deserialize JSON string to a POJO containing list of objects but I keep running into this error:

Cannot construct instance of com.response.dto.RootDTO (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('Meta') at [Source: (String)""Meta":[{"DimensionName":"Version","DimensionId":"3b4860b9-b215-4192-bd7a-a76f377fc465","DimensionType":"Regular","Alias":"C0","AttributeId":"211d5-d91f-40ec-9668-20e0da2ae7b3","AttributeName":"Version Name","AttributeKey":"VersionKey"; line: 1, column: 1]

This is what my JSON string looks like (but with escape chars in eclipse):

{"Meta":[{"DimensionName":"Version", "DimensionId":"3b4860b9-b215-4192-bd7a-a76f377fc465, "DimensionType":"Regular","Alias":"C0","AttributeId":"211b33d5-d91f-40ec-9668-20e0da2ae7b3","AttributeName":"Version Name","AttributeKey":"VersionKey"}]}.

Here is the class I want to deserialize it to:

@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class RootDTO 
{
  @JsonProperty("Meta")
  private List Meta;
}


 @JsonIgnoreProperties(ignoreUnknown = true)
 @Data
 public class MetaDTO 
{

 @JsonProperty("DimensionName")
 private String DimensionName;

 @JsonProperty("AttributeId")
 private String AttributeId;

 @JsonProperty("AttributeName")
 private String AttributeName;

 @JsonProperty("Name")
 private String Name;

 @JsonProperty("Alias")
 private String Alias;
}

This is the code that blows up when trying to read the value:

 ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        
  objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
         
        objectMapper.readValue(jsonFormattedString, RootDTO.class));
         

I only see this issue while running Junit (version : 4.12). I see jackson-databind-2.11.0, spring-test-5.2.7.RELEASE in the stack trace. However, I debug using a call from browser or postman it works fine. I am not sure why it is looking for the string Meta when I have specified it to be a list. What could be causing this issue? Any suggestions?

Edit: Turns out that the string which was being supplied to the ObjectMapper isn't the correct one. There is this line of code String jsonFormattedString = responseEntity.getBody().substring(1, responseEntity.getBody().lastIndexOf("\"")).replaceAll("\\\\", ""); which makes my mocked string invalid. I'll need to figure out why we are doing this though.

java json spring-boot jackson objectmapper