Home > Software engineering >  Cannot deserialize value of type `java.lang.String` from Array value from mockmvc
Cannot deserialize value of type `java.lang.String` from Array value from mockmvc

Time:02-11

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());

CodePudding user response:

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;
}

CodePudding user response:

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

  • Related