Unmarshall json #POST parameter - java

I have a class looking like this:
public class Test {
#JsonProperty("name")
private String name;
public Test(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Also there is an endpoint class using javax.ws.rs:
#Path("/Test")
public class Endpoint {
#POST
#Consumes("application/json")
#Produces("application/json")
#HeaderParam("Accept") #DefaultValue("application/json")
public Response createTest(String json) {
return Response.status(Response.Status.ACCEPTED).entity(json).build();
}
}
This works as expected.
Question: How can I make createTest() take the "Test" class as a parameter instead of "String"?
Trial: Sending the following gives "415 Unsupported Media Type" when using "Test" as a paramter to createTest():
POST ../Endpoint/ HTTP/1.1
Host: localhost:8080
Accept: application/json
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 56d06798-2b32-57fc-c22a-0240aceb8f98
{
"name": "Kalle"
}

I think you have to use Jersey 2.xx version.
public class LoginRequest {
private String userName;
private String password;
public LoginRequest(){
super();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Your Resource with a Bean (here goes your Bean Test)
#POST
#Path("login")
#Consumes(MediaType.APPLICATION_JSON)
public Response login(LoginRequest request) {
....
}
and the dependecies:
<properties>
<jersey.version>2.22.1</jersey.version>
<jackson.version>2.6.1</jackson.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<version>1</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
The reason 415 Unsupported Media Type issue is because you don't have the correct dependecies.
... have fun

Related

Spring wont deserialize Object when content is Application/JSON

I am try to create an endpoint in spring where I sent raw JSON and it will not deserialize to object but if I use form Data it works fine. I am just wondering what I did wrong?
this is the object
#Document("Boats")
#NoArgsConstructor
#AllArgsConstructor
#Getter
#Setter
public class Boat{
#Id
private String id;
private Boolean online;
private String boatName;
private String lastOnline;
private String password;
#JsonIgnore
#Transient
private java.net.InetAddress inetAddress;
private String displayAddress;
private String displayStatus;
public Boat(String boatName, InetAddress inetAddress,Boolean online) {
this.online = online;
this.boatName = boatName;
this.inetAddress = inetAddress;
this.displayAddress = inetAddress.getHostAddress();
if(online){
String pattern = "E, dd MMM yyyy HH:mm:ss z";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("CST"));
this.lastOnline = simpleDateFormat.format(new Date());
}
updateDisplayStatus();
}
public void updateDisplayStatus(){
if(getOnline()){
setDisplayStatus(BoatStatus.ONLINE.getDisplayText());
}else{
setDisplayStatus(BoatStatus.OFFLINE.getDisplayText());
}
}
}
and this is the endpoint
#PostMapping(path= "/boat/update")
public ResponseEntity updateBoat(#RequestBody Boat boat){
boatFacade.updateBoat(boat);
return ResponseEntity.ok().build();
}
this is the body of the request
{
"id":"62ca4f7c5a3e0f1411445065",
"online":"false",
"boatName":"dfsjkdfsd",
"lastOnline":"null",
"password":"null",
"displayAddress":"10.50.50.50",
"displayStatus":"ONLINE"
}
these are the POM dependencies I am using not sure if I am missing
a dependency
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
It is always recommended to specify the Type/Kind of data that your endpoint consume/produce.
#PostMapping(value = "/boat/update", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
Object reserializes - debug Point
PostMan Setting

Java JsonIgnore is not hiding field

Need to hide one field from Json, but leave it, because need to use it in another method ( get ). Tried to do it, but id field is still visible in Json. Whats wrong here?
Dependencies:
<properties>
<!-- Use the latest version whenever possible. -->
<jackson.version>2.4.4</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>catalina</artifactId>
<version>6.0.53</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>8.0.53</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.bundles/jaxrs-ri -->
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.31</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
Trying to do it this way:
package test.model;
import java.math.BigDecimal;
import test.model.DbTest;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(value = { "id" })
public final class Home {
#JsonIgnore
private final BigDecimal id;
private final String date;
public Home( //
BigDecimal id, //
String date) {
this.id = id;
this.date = date;
}
public final BigDecimal getId() {
return id;
}
public final String getDate() {
return date;
}
public static final Home newInstance(
DbTest test) {
return new Home(
test.getId(),
test.getDate());
}
}
Try using this in pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.4</version>
</dependency>
or remove 'final' from field

Spring Boot Project - Issue with writing JPQL (Intellij)

So I have setup a spring boot project with which I'd like to create some specific queries.
Very simple, I just want to execute a select statement:
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
#PersistenceContext
private EntityManager entityManager;
public User findUserByEmail(String email) {
Query nativeQuery = entityManager.createQuery("select e from User");
nativeQuery.getFirstResult();
return new User();
}
}
In Intellij, when I hover over User it says cannot resolve symbol for User, I've had a google and most of the answers say you need to use the name of the entity, which of course I did:
#Entity(name = "PG_user")
public class User extends AbstractEntity {
#Column
private String email;
#Column
private String password;
public User(){}
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;
}
}
Here is my POM also, if this helps:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>0.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.2.2.jre8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.webjars.bower/angular-bootstrap-contextmenu -->
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>angular-bootstrap-contextmenu</artifactId>
<version>0.9.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-crypto -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.0-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
</dependencies>
But the name of your entity is PG_user
#Entity(name = "PG_user")
public class User extends AbstractEntity {
The name attribute defines the name of the entity that you must use for querying.
But I assume you want to set the name of the table.
That would be
#Table(name = "PG_user")
#Entity
public class User extends AbstractEntity {

404 not found in RestController in Spring Boot

I have a Spring Boot Project with pom.xml like this
<groupId>com.project</groupId>
<artifactId>prj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>prj</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
The Application class is like this
#SpringBootApplication
public class PrjApplication {
public static void main(String[] args) {
SpringApplication.run(HqApplication.class, args);
}
}
And I have a RestController where I am trying to do some CRUD Operations like this
#RestController("/register")
public class RegisterController {
#Autowired
private UserRepository userRepository;
#GetMapping("/user/{id}")
public User getUser(#Valid #RequestBody Long id){
User user = userRepository.getOne(id);
return user;
}
#PostMapping("/new")
public User saveUser(#Valid #RequestBody String name,#Valid #RequestBody String email,#Valid #RequestBody String password,#Valid #RequestBody String phone){
System.out.println("savginv user");
User user = new User();
user.setEmail(email);
user.setPassword(password);
user.setName(name);
user.setPhone(phone);
userRepository.save(user);
return user;
}
}
I have made an Entity class; User like this
#Entity
#Table(name = "tbl_users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name, email, password, phone;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
When I try to save a user by calling the post method using PostMan it gives me 404 not found error.
{
"timestamp": "2018-06-23T06:47:14.086+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/prj/register/new"
}
I am using JPARepository to perform Database operations.
/prj isn't part of your controller. Either use a POST request without it (i.e., /register/new), or add it to your controller's mapping:
#RestController("/prj/register")
public class RegisterController {
// rest of the code (no pun intended)

Java Spring - 415 Unsupported Media Type

Here is my Controller:
#RestController
public class UserController {
#RequestMapping(value = "/test", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public User someName(#RequestBody User user){
System.out.println(user.toString());
return user;
}
}
User class:
#Entity
#Table(name = "user")
public class User {
#Id #GeneratedValue
#Column(name = "id")
private Integer id;
private String name;
private String secondname;
private String email;
public User() {
}
public User(Integer id, String name, String secondname, String email) {
this.id = id;
this.name = name;
this.secondname = secondname;
this.email = email;
}
public User(String name, String secondname, String email) {
this.name = name;
this.secondname = secondname;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "secondname")
public String getSecondname() {
return secondname;
}
public void setSecondname(String secondname) {
this.secondname = secondname;
}
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return new StringBuilder().append(this.name).append(", ").append(this.secondname).append(", ")
.append(this.email).toString();
}
}
And my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pl</groupId>
<artifactId>javalab</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>javalab Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<java-version>1.7</java-version>
</properties>
<repositories>
<!-- Repository for ORACLE JDBC Driver -->
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Servlet API -->
<!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Jstl for jsp page -->
<!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- JSP API -->
<!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- Spring dependencies -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- Hibernate -->
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.8.Final</version>
</dependency>
<!-- MySQL JDBC driver -->
<!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- Oracle JDBC driver -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- SQLServer JDBC driver (JTDS) -->
<!-- http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Mail Start -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- Mail End -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
</dependencies>
<build>
<finalName>javalab</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
</project>
When I want to post in in postman:
{
"name": "test",
"secondname": "test",
"email": "test#test.pl"
}
I have an error: 415 Unsupported Media type
More precisely I have: The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
In postman I choose raw and JSON (application/json). As headers I have written: Content-Type as key and application/json as value.
Somebody have any idea what I'm doing wrong?
You can use the chrome's inspect to see the HTTP header of your postman's request.Check whether the content-Type is corrent.
This is so common in spring. Make your entity serializable.

Categories