Saturday 9 September 2023

Error Cannot construct instance of `com.UserModel.Models.Users` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (okhttp3.ResponseBody$BomAwareReader); line: 3, column: 3]

The error message you're seeing suggests that Jackson is unable to deserialize the XML response from the API into the Users class. Specifically, the error message says that no creators (like a default constructor) exist for the Users class, so Jackson is unable to construct an instance of the class.

To resolve this issue, you can try one of the following solutions:

  1. Add a default constructor to the Users class: One solution is to add a default constructor to the Users class. This will allow Jackson to create instances of the class during deserialization. You can add a default constructor like this:

public Users() { // Default constructor }

  1. Add a custom deserializer for the Users class: Another solution is to create a custom deserializer for the Users class. This will allow you to specify how Jackson should construct instances of the class during deserialization. You can create a custom deserializer like this:

public class UsersDeserializer extends StdDeserializer<Users> { public UsersDeserializer() { this(null); } public UsersDeserializer(Class<?> vc) { super(vc); } @Override public Users deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); // Parse the JSON node and create a new instance of the Users class int userId = node.get("userId").asInt(); String userName = node.get("userName").asText(); String userRole = node.get("userRole").asText(); return new Users(userId, userName, userRole); } }

Then, you can register the custom deserializer with the ObjectMapper instance like this:

XmlMapper mapper = new XmlMapper(); SimpleModule module = new SimpleModule(); module.addDeserializer(Users.class, new UsersDeserializer()); mapper.registerModule(module);

These solutions should help you resolve the no Creators, like default constructor, exist error that you're seeing.

No comments:

Post a Comment