"Content type 'application/json;charset=UTF-8' not supported" in Spring Rest application
Asked Answered
S

15

34

When I do a POST request on localhost:8080/api/users to create a new user I get the following error :

{
    "timestamp": "2018-05-28T09:44:55.704+0000",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/json;charset=UTF-8' not supported",
    "path": "/api/users/"
}

enter image description here

Here is the request's body, JSON (application/json) is selected.

It gives the same error even if I remove the Roles and keep it null.

enter image description here

The header's content type is application/json as well.

enter image description here

This is my controller :

@PostMapping("/api/users" )
public User createUser(@Valid @RequestBody User user) {
    securityService.autologin(user.getUsername(), user.getPassword());
    return userService.createUser(user);
}

createUser function in UserService :

public User createUser(@Valid @RequestBody User user) {
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    user.setRoles(new HashSet<>(roleRepository.findAll()));
    return userRepository.save(user);
}

edit

This is my User class :

@Entity
@Table(name = "user")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, 
                      allowGetters = true)
public class User implements Serializable{

    private static final long serialVersionUID = 1L;
    
    
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "user_name")
    private String name;

    @Column(name = "user_email")
    private String email;
    
    @Column(name = "user_password")
    @NotBlank
    private String password;
    
    @Column(name = "user_status")
    private String status;
    
    @Column(name = "user_tel")
    private String tel;
    
    @Column(name = "user_confirmation")
    private String confirmation;

    @Column(name = "user_birth_date")
    @Temporal(TemporalType.DATE)
    private Date birth_date;
    
    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date updatedAt;

    @JsonManagedReference
    @ManyToMany
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;
    
    @Column(name = "username")
    @NotBlank
    private String username;
    
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getConfirmation() {
        return confirmation;
    }

    public void setConfirmation(String confirmation) {
        this.confirmation = confirmation;
    }

    public Date getBirth_date() {
        return birth_date;
    }

    public void setBirth_date(Date birth_date) {
        this.birth_date = birth_date;
    }

    public Date getCreatedAt() {
        return createdAt;
    }
    
    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }
    
    public Set<Role> getRoles() {
        return roles;
    }
    
    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}
Spangler answered 28/5, 2018 at 9:52 Comment(12)
Are you using RestController or simple Controller ?Allo
@Ouissal: Refer: https://mcmap.net/q/190596/-post-to-jersey-rest-service-getting-error-415-unsupported-media-type and Add Content-Type: application/json and Accept: application/jsonNormand
@Spangler Also make sure you have placed JAXB annotation in your Entity i.e. User classRecreant
Why would you need JAXB annotations for JSON conversión?Hamza
Have you configured any Jackson or Gson converters for your application?Hamza
@EdwinDalorzo I meant annotation responsible for serializing deserializing to-from json. Just assumed JAXB/Jackson as serializer and hence askedRecreant
Jackson may use JAXB annotations if the mapper is configured to do so, but that’s not required. On the other hand that would cause an entire different error.Hamza
May be because Authorization Header..I am not sure but try to remove authorization header.Amrita
@RohitKavathekar I tried removing it and still got the same errorSpangler
@EdwinDalorzo I have edited my question and added my User entitySpangler
github.com/Ouissalb/SpringRestAppSpangler
If you land here instead because your @RequestBody InputStream declaration isn't working (nothing to do with JSON mappings), try @RequestBody InputStreamResource insteadPortmanteau
S
27

I was able to solve it by removing @JsonManagedReference.

Spangler answered 28/5, 2018 at 13:30 Comment(2)
This solution worked in my case.Balderdash
A bit weird, but it helped - removed @JsonManagedReference from the entity, not involved in this particular place/request/endpoint. The more strange thing is - annotated entity did not cause any issues in other places...Precession
E
22

In my case there was a Jackson fail, logged as a WARN:

Failed to evaluate Jackson deserialization for type [[simple type, class ***]]: com.fasterxml.jackson.databind.JsonMappingException: Conflicting setter definitions for property [...]

I had overloaded a setter by accident, so it could not be resolved by Jackson and spring has thrown 415.

Eboat answered 28/5, 2020 at 10:20 Comment(1)
THis helped me solve my issue. I was using @JsonProperty("fooPerson") to try and deserialize the key into something different than the variable name. It wasn't liking thatEellike
F
7

In my case I Had two times the same identifier for jsonProperty in my dto class When I made the request return: "Content type 'application/json;charset=UTF-8" Not sure why return that error but once I changed the identifier it works.

enter image description here

Flyboat answered 12/5, 2023 at 21:35 Comment(0)
E
2

You can try something like

@PostMapping(value="/rest/account/json", consumes={"application/json"})

Embouchure answered 28/5, 2018 at 9:59 Comment(3)
I get this error : "Type mismatch: cannot convert from MediaType to String[]"Spangler
@Ouissal: Try this once, MediaType.APPLICATION_JSON_VALUE instead of MediaType.APPLICATION_JSONNormand
Clearly the OP is getting a. different error now. So, your answer was probably correct. This seems to be a lack of message converters now.Hamza
T
2

You specified content-type = application/json. I think you may have to check also "Accept" Header property (application/json)

postman screenshot

Turku answered 21/11, 2018 at 15:3 Comment(0)
H
2

I was also encountering this Error as WARN with Jackson deserialization. My situation more closely related to the response from Klaudia where I had a member field on my POJO for a Service that I had marked with @JsonIgnore, but I had renamed my getter and setter to getService() and setService() for brevity instead of the variable name which matched a longer named Service Interface. Adding @JsonIgnore to the differently named getter and setter resolved the error.

Harrus answered 20/3, 2021 at 19:14 Comment(0)
K
1

There can be the case when someone mistakenly keeps 2 getters for the same property and Jackson deserialization fails to evaluate.

It throws

Failed to evaluate Jackson deserialization for type [[simple type,
class com.org..*..*]]:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Conflicting getter definitions for property \"field_name\":
com.org..*..*#getterBName() vs com.org..*..*#gettername()"

In that case, just remove the extra getter of that field.

Kelso answered 27/1, 2021 at 6:15 Comment(0)
H
0

It clearly says Unsupported Media type which means due to any issue the call to operation cannot be completed. so check what your service operation is asking for and are you sending all the fields correctly. Most of the time there is mapping issue. Check console for errors.

Hedvig answered 10/4, 2019 at 12:15 Comment(0)
B
0

I also encounter this error while using following with a PATCH request:

public Order markOrderAsPayed(@RequestBody final MultiValueMap<String, String> values) {
...
}

The MultiValueMap is from org.springframework.util. Changing the Map to Map<String, String> resolved the problem for me.

Sorry, but I can't give an explanation why.

Berwickupontweed answered 15/9, 2021 at 21:2 Comment(0)
F
0

may be too late for this post.

if you can add this media type in your controller class for consumes={MediaType.APPLICATION_JSON_UTF8_VALUE} you can get pass this.

Fishwife answered 29/10, 2021 at 22:7 Comment(0)
M
0

Try removing charset from header Content-type, application json only, and it will probably work.

Misanthropy answered 13/2, 2022 at 22:3 Comment(0)
S
0

I had the same issue when using @PutMapping and @RequestBody MultiValueMap<String,String>. I changed the MultiValueMap to Map and it worked, just like what edta had suggested above.

Semang answered 18/12, 2022 at 12:33 Comment(1)
This is similar to my case.Decrypt
B
0

I had similar problem, which caused from the mismatch of JsonBackReference and JsonManagedReference's values. @JsonBackReference(value = "parent - address - reference") vs @JsonManagedReference(value = "parent - address reference")

Bonita answered 8/1 at 10:53 Comment(0)
M
-1

Set @Produces(MediaType.APPLICATION_JSON) to your function to set it in json mime type.

You can check that restapi for more informations.

Moro answered 28/5, 2018 at 9:57 Comment(6)
That would be @Consumes(MediaType.APPLICATION_JSON)Nabors
"Type mismatch: cannot convert from MediaType to String[]"Spangler
@Ouissal: Try this once, MediaType.APPLICATION_JSON_VALUE instead of MediaType.APPLICATION_JSONNormand
@gaurav When I change to that I get this error : BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource ...: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Invalid mapping on handler class [......UserRestController]...Spangler
caused by this "Invalid mime type "MediaType.APPLICATION_JSON_VALUE": does not contain '/'"Spangler
@Spangler : Can you create a Minimal, Complete, and Verifiable example? Post it on github and we can fix the issue. Its hard to solve new issues just by looking at the Exceptions.Normand
C
-1

You can use "application/json" instead

enter image description here

Cleanse answered 17/1, 2020 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.