'Cannot deserialize value of type `java.lang.String` from Array value from mockmvc

public class ModelDTO implements Serializable {

    private Long id;
    private String datasetName;
 
    @JsonRawValue
    private String json;
}

Post API is working fine from postman or swagger if I send the following body.

{
  "id": 1,
  "datasetName": "Insurance",
  "json" : "[{\"ClassName\":\"AAAA\",\"Fields\":[[\"cdsa\",\"csa\"],[\"ca\"]]},{\"ClassName\":\"ca\",\"Fields\":[null]}]"
}

But MockMVC test case is giving follwing error in Spring boot project

Bad Request: JSON parse error: Unexpected character ('C' (code 67)): was expecting comma to separate Object entries; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('C' (code 67)): was expecting comma to separate Object entries at [Source: (PushbackInputStream); line: 1, column: 89]

mockMvc.perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(ModelDTO))).andExpect(status().isCreated());


Solution 1:[1]

I believe you don't actually need @JsonRawValue so try removing it:

public class ModelDTO implements Serializable {
    private Long id;
    private String datasetName;
    private String json;
}

Solution 2:[2]

my json were not properly set. it requires backword slash for parsing. I have added extra two backword slash like '\' and now it is working.

private static final String DEFAULT_JSON = "\"[{\\\"ClassName\\\":\\\"Health Aditya Birla\\\",\\\"Fields\\\":[[\\\"Insured Person's Details\\\",\\\"Gender\\\",\\\"Member ID\\\"],[\\\"Policy Details\\\",\\\"Insured Person's Details\\\"],[\\\"Premium Certificate\\\"]]},{\\\"ClassName\\\":\\\"Health Care\\\",\\\"Fields\\\":[[\\\"Details of Insured\\\",\\\"Relationship\\\",\\\"Date Of Birth\\\"],[\\\"Mobile No\\\"],[\\\"Gross Premium\\\",\\\"Goods & Services Tax\\\"]]}]\"";

I have referred following link to solve this issue.

enter link description here

Solution 3:[3]

In my case I had incorrect Type definition. e.g.

public class ModelDTO implements Serializable {

    private Long id;
    private String datasetName;
 
    private String part;
}

So I had to correct it as:

public class ModelDTO implements Serializable {

    private Long id;
    private String datasetName;
 
    private List<String> part;
}

That solved my issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 João Dias
Solution 2 rhl mngl
Solution 3