Issue
I am using SpringBoot with Mongo database and I am trying to save embedded documents into database.
I have this model:
Profile.java
@Data
@Document
public class Profile {
public final City city;
public final String imageId;
public Profile(City city,
String imageId) {
this.city = city;
this.imageId = imageId;
}
@Override
public String toString() {
return "Profile{" +
", city=" + city +
", imageId='" + imageId + '\'' +
'}';
}
private static boolean atLeast(int numChars, String s) {
if (s == null) {
return false;
}
var str = s.strip();
return str.length() >= numChars;
}
public static ProfileBuilder builder() {
return new ProfileBuilder();
}
public static final class ProfileBuilder {
public City city;
public String imageId;
private ProfileBuilder() {
}
public ProfileBuilder withCity(City city) {
this.city = city;
return this;
}
public ProfileBuilder withImageId(String imageId) {
this.imageId = imageId;
return this;
}
public Profile build(){
return new Profile(city, imageId);
}
}
}
City.java
public class City {
public final String name;
public City(String name) {
this.name = name;
}
@Override
public String toString() {
return "City{" +
", name='" + name + '\'' +
'}';
}
}
ProfileController.java
@RequestMapping( method = RequestMethod.POST)
public Profile addUser(@RequestBody Profile profile) {
return profileService.addProfile(profile);
}
and with postman I am sending this JSON
{
"city":{
"name":"Atena"
},
"imageId" : "Doe",
}
}
But I am getting following error:
"JSON parse error: Cannot construct instance of `domain.City` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator);"
Solution
There are at least two solutions.
- Add
@JsonCreator
to constructor and@JsonProperty
to its arguments (to instruct Jackson how to substitute JSON items into constructor in proper order)
class Profile {
...
@JsonCreator
public Profile(@JsonProperty("city") City city,
@JsonProperty("imageId") String imageId) {
this.city = city;
this.imageId = imageId;
}
...
}
(+ same for City class)
- Un
final
class properties and provide default no-arg constructor (along with existing all-arg constructor).
class Profile {
public City city;
public String imageId;
public Profile() {
}
public Profile(City city, String imageId) {
this.city = city;
this.imageId = imageId;
}
}
(+ same for City class)
Test
class Test {
public static void main(String[] args) throws JsonProcessingException {
String json = "{\"city\":{\"name\":\"Atena\"},\"imageId\":\"Doe\"}";
Profile p = new ObjectMapper().readValue(json, Profile.class);
System.out.println(p);
}
}
Output:
Profile{, city=City{, name='Atena'}, imageId='Doe'}
Answered By - Nikolai Shevchenko
Answer Checked By - David Goodson (JavaFixing Volunteer)