Средство записи тела сообщения для java.util.Список массивов и тип Java java.util.ListUserEntity> и приложение типа MIME-носителя/json не найдено

#java #json #jersey #mime

Вопрос:

Я пытаюсь заставить работать веб-службу, которая возвращает JSON. Цель состоит в том, чтобы отобразить все элементы моей базы данных SQL. Однако я получаю исключение ниже. Я рассматривал подобные проблемы, но ни одно из решений не работает для меня. У вас есть какие-нибудь предложения? Спасибо!

Ошибка :

 28-Nov-2021 15:48:45.769 INFO [http-nio-8080-exec-4] org.hibernate.jpa.internal.util.LogHelper.logPersistenceUnitInformation HHH000204: Processing PersistenceUnitInfo [name: default] 28-Nov-2021 15:48:46.028 INFO [http-nio-8080-exec-4] org.hibernate.Version.logVersion HHH000412: Hibernate ORM core version 5.5.7.Final 28-Nov-2021 15:48:46.703 INFO [http-nio-8080-exec-4] org.hibernate.annotations.common.reflection.java.JavaReflectionManager.lt;clinitgt; HCANN000001: Hibernate Commons Annotations {5.1.2.Final} 28-Nov-2021 15:48:47.244 WARN [http-nio-8080-exec-4] org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH10001002: Using Hibernate built-in connection pool (not for production use!) Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary. 28-Nov-2021 15:48:47.261 INFO [http-nio-8080-exec-4] org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test_atos] 28-Nov-2021 15:48:47.263 INFO [http-nio-8080-exec-4] org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator HHH10001001: Connection properties: {password=****, user=root} 28-Nov-2021 15:48:47.263 INFO [http-nio-8080-exec-4] org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator HHH10001003: Autocommit mode: false 28-Nov-2021 15:48:47.275 INFO [http-nio-8080-exec-4] org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.lt;initgt; HHH000115: Hibernate connection pool size: 20 (min=1) 28-Nov-2021 15:48:47.858 INFO [http-nio-8080-exec-4] org.hibernate.dialect.Dialect.lt;initgt; HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect 28-Nov-2021 15:48:49.872 INFO [http-nio-8080-exec-4] org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator.initiateService HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] 28-Nov-2021 15:48:50.119 SEVERE [http-nio-8080-exec-4] com.sun.jersey.spi.container.ContainerResponse.write A message body writer for Java class java.util.ArrayList, and Java type java.util.Listlt;entities.UserEntitygt;, and MIME media type application/json was not found. The registered message body writers compatible with the MIME media type are: application/json -gt;  com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$App  com.sun.jersey.json.impl.provider.entity.JSONArrayProvider$App  com.sun.jersey.json.impl.provider.entity.JSONObjectProvider$App  com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$App  com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$App */* -gt;  com.sun.jersey.core.impl.provider.entity.FormProvider  com.sun.jersey.core.impl.provider.entity.StringProvider  com.sun.jersey.core.impl.provider.entity.ByteArrayProvider  com.sun.jersey.core.impl.provider.entity.FileProvider  com.sun.jersey.core.impl.provider.entity.InputStreamProvider  com.sun.jersey.core.impl.provider.entity.DataSourceProvider  com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General  com.sun.jersey.core.impl.provider.entity.ReaderProvider  com.sun.jersey.core.impl.provider.entity.DocumentProvider  com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider  com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter  com.sun.jersey.server.impl.template.ViewableMessageBodyWriter  com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$General  com.sun.jersey.json.impl.provider.entity.JSONArrayProvider$General  com.sun.jersey.json.impl.provider.entity.JSONObjectProvider$General  com.sun.jersey.json.impl.provider.entity.JSONWithPaddingProvider  com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General  com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General  com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$General  com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General  com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy  28-Nov-2021 15:48:50.120 SEVERE [http-nio-8080-exec-4] com.sun.jersey.spi.container.ContainerResponse.logException Mapped exception to response: 500 (Internal Server Error)  javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class java.util.ArrayList, and Java type java.util.Listlt;entities.UserEntitygt;, and MIME media type application/json was not found.   at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:284)  at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1510)  at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)  at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)  at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)  at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)  at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)  at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)  at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)  at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:346)  at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)  at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)  at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:887)  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1684)  at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)  at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)  at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)  at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)  at java.base/java.lang.Thread.run(Thread.java:834)  Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class java.util.ArrayList, and Java type java.util.Listlt;entities.UserEntitygt;, and MIME media type application/json was not found.   ... 30 more  

Файл пользователя :

 package entities;  import javax.persistence.*; import java.sql.Date;  @Entity @Table(name = "user", schema = "test_atos") public class UserEntity {  private int id;  private String username;  private Date birthday;  private String country;  private String phone;  private String gender;   @Id  @Column(name = "id", nullable = false)  public int getId() {  return id;  }   public void setId(int id) {  this.id = id;  }   @Basic  @Column(name = "username", nullable = false, length = 100)  public String getUsername() {  return username;  }   public void setUsername(String username) {  this.username = username;  }   @Basic  @Column(name = "birthday", nullable = false)  public Date getBirthday() {  return birthday;  }   public void setBirthday(Date birthday) {  this.birthday = birthday;  }   @Basic  @Column(name = "country", nullable = false)  public String getCountry() {  return country;  }   public void setCountry(String country) {  this.country = country;  }   @Basic  @Column(name = "phone", nullable = true, length = 20)  public String getPhone() {  return phone;  }   public void setPhone(String phone) {  this.phone = phone;  }   @Basic  @Column(name = "gender", nullable = true)  public String getGender() {  return gender;  }   public void setGender(String gender) {  this.gender = gender;  }   @Override  public boolean equals(Object o) {  if (this == o) return true;  if (o == null || getClass() != o.getClass()) return false;   UserEntity that = (UserEntity) o;   if (id != that.id) return false;  if (username != null ? !username.equals(that.username) : that.username != null) return false;  if (birthday != null ? !birthday.equals(that.birthday) : that.birthday != null) return false;  if (country != null ? !country.equals(that.country) : that.country != null) return false;  if (phone != null ? !phone.equals(that.phone) : that.phone != null) return false;  if (gender != null ? !gender.equals(that.gender) : that.gender != null) return false;   return true;  }   @Override  public int hashCode() {  int result = id;  result = 31 * result   (username != null ? username.hashCode() : 0);  result = 31 * result   (birthday != null ? birthday.hashCode() : 0);  result = 31 * result   (country != null ? country.hashCode() : 0);  result = 31 * result   (phone != null ? phone.hashCode() : 0);  result = 31 * result   (gender != null ? gender.hashCode() : 0);  return result;  } }  

UserRESTAPI file :

 package atos.api;  import entities.UserEntity;  import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.List;  @Path("/user") public class UserRESTAPI {   @GET  @Produces(MediaType.APPLICATION_JSON)  @Path("")   public Listlt;UserEntitygt; getAll(){  EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");  EntityManager em = emf.createEntityManager();   Listlt;UserEntitygt; u = em.createNativeQuery("SELECT * FROM user", UserEntity.class).getResultList();  return u;  } }  

pom.xml file

 lt;?xml version="1.0" encoding="UTF-8"?gt; lt;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/xsd/maven-4.0.0.xsd"gt;  lt;modelVersiongt;4.0.0lt;/modelVersiongt;  lt;groupIdgt;com.examplelt;/groupIdgt; lt;artifactIdgt;userAtosAPIlt;/artifactIdgt; lt;versiongt;1.0-SNAPSHOTlt;/versiongt; lt;namegt;userAtosAPIlt;/namegt; lt;packaginggt;warlt;/packaginggt;  lt;propertiesgt;  lt;project.build.sourceEncodinggt;UTF-8lt;/project.build.sourceEncodinggt;  lt;maven.compiler.targetgt;1.8lt;/maven.compiler.targetgt;  lt;maven.compiler.sourcegt;1.8lt;/maven.compiler.sourcegt;  lt;junit.versiongt;5.7.1lt;/junit.versiongt; lt;/propertiesgt;  lt;dependenciesgt;   lt;dependencygt;  lt;groupIdgt;junitlt;/groupIdgt;  lt;artifactIdgt;junitlt;/artifactIdgt;  lt;versiongt;3.8.1lt;/versiongt;  lt;scopegt;testlt;/scopegt;  lt;/dependencygt;    lt;!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --gt;  lt;dependencygt;  lt;groupIdgt;javax.servletlt;/groupIdgt;  lt;artifactIdgt;javax.servlet-apilt;/artifactIdgt;  lt;versiongt;3.1.0lt;/versiongt;  lt;scopegt;providedlt;/scopegt;  lt;/dependencygt;   lt;!-- https://mvnrepository.com/artifact/asm/asm --gt;  lt;dependencygt;  lt;groupIdgt;asmlt;/groupIdgt;  lt;artifactIdgt;asmlt;/artifactIdgt;  lt;versiongt;3.3.1lt;/versiongt;  lt;/dependencygt;   lt;!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle --gt;  lt;dependencygt;  lt;groupIdgt;com.sun.jerseylt;/groupIdgt;  lt;artifactIdgt;jersey-bundlelt;/artifactIdgt;  lt;versiongt;1.19.2lt;/versiongt;  lt;/dependencygt;   lt;!-- https://mvnrepository.com/artifact/org.json/json --gt;  lt;dependencygt;  lt;groupIdgt;org.jsonlt;/groupIdgt;  lt;artifactIdgt;jsonlt;/artifactIdgt;  lt;versiongt;20160810lt;/versiongt;  lt;/dependencygt;   lt;!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-server --gt;  lt;dependencygt;  lt;groupIdgt;com.sun.jerseylt;/groupIdgt;  lt;artifactIdgt;jersey-serverlt;/artifactIdgt;  lt;versiongt;1.19.2lt;/versiongt;  lt;/dependencygt;   lt;dependencygt;  lt;groupIdgt;com.sun.jerseylt;/groupIdgt;  lt;artifactIdgt;jersey-jsonlt;/artifactIdgt;  lt;versiongt;1.8lt;/versiongt;  lt;/dependencygt;   lt;!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-core --gt;  lt;dependencygt;  lt;groupIdgt;com.sun.jerseylt;/groupIdgt;  lt;artifactIdgt;jersey-corelt;/artifactIdgt;  lt;versiongt;1.19.2lt;/versiongt;  lt;/dependencygt;  lt;dependencygt;  lt;groupIdgt;mysqllt;/groupIdgt;  lt;artifactIdgt;mysql-connector-javalt;/artifactIdgt;  lt;versiongt;8.0.25lt;/versiongt;  lt;/dependencygt;   lt;dependencygt;  lt;groupIdgt;com.fasterxml.jackson.corelt;/groupIdgt;  lt;artifactIdgt;jackson-databindlt;/artifactIdgt;  lt;versiongt;2.9.8lt;/versiongt;  lt;/dependencygt;   lt;dependencygt;  lt;groupIdgt;org.hibernatelt;/groupIdgt;  lt;artifactIdgt;hibernate-corelt;/artifactIdgt;  lt;versiongt;5.5.7.Finallt;/versiongt;  lt;/dependencygt; lt;/dependenciesgt;  lt;buildgt;  lt;pluginsgt;  lt;plugingt;  lt;groupIdgt;org.apache.maven.pluginslt;/groupIdgt;  lt;artifactIdgt;maven-war-pluginlt;/artifactIdgt;  lt;versiongt;3.3.1lt;/versiongt;  lt;/plugingt;  lt;/pluginsgt; lt;/buildgt; lt;/projectgt;  

persistance.xml file

 lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?gt; lt;persistence xmlns="https://jakarta.ee/xml/ns/persistence"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"  version="3.0"gt;  lt;persistence-unit name="default"gt;   lt;classgt;entities.UserEntitylt;/classgt;  lt;propertiesgt;  lt;property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test_atos"/gt;  lt;property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/gt;  lt;property name="hibernate.connection.user" value="root"/gt;  lt;property name="hibernate.connection.password" value=""/gt;  lt;/propertiesgt;  lt;/persistence-unitgt; lt;/persistencegt;  

web.xml файл

 lt;?xml version="1.0" encoding="UTF-8"?gt; lt;web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"  version="4.0"gt;   lt;servletgt;  lt;servlet-namegt;jerseyServletlt;/servlet-namegt;  lt;servlet-classgt;com.sun.jersey.spi.container.servlet.ServletContainerlt;/servlet-classgt;  lt;init-paramgt;  lt;param-namegt;com.sun.jersey.config.property.packageslt;/param-namegt;  lt;param-valuegt;atos.apilt;/param-valuegt;  lt;/init-paramgt;   lt;init-paramgt;  lt;param-namegt;com.sun.jersey.api.json.POJOMappingFeaturelt;/param-namegt;  lt;param-valuegt;truclt;/param-valuegt;  lt;/init-paramgt;  lt;load-on-startupgt;1lt;/load-on-startupgt;  lt;/servletgt;  lt;servlet-mappinggt;  lt;servlet-namegt;jerseyServletlt;/servlet-namegt;  lt;url-patterngt;/api/*lt;/url-patterngt;  lt;/servlet-mappinggt;  lt;/web-appgt; lt;!-- end snippet --gt;  hibernate.cfg.xml file  lt;!-- begin snippet: js hide: false console: true babel: false --gt;  lt;!-- language: lang-js --gt; lt;?xml version='1.0' encoding='utf-8'?gt; lt;!DOCTYPE hibernate-configuration PUBLIC  "-//Hibernate/Hibernate Configuration DTD//EN"  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"gt; lt;hibernate-configurationgt;  lt;session-factorygt;  lt;property name="hibernate.connection.driver_class"gt;com.mysql.cj.jdbc.Driverlt;/propertygt;  lt;property name="hibernate.connection.url"gt;jdbc:mysql://localhost:3306/test_atoslt;/propertygt;  lt;property name="hibernate.connection.username"gt;rootlt;/propertygt;  lt;property name="hibernate.connection.password"gt;lt;/propertygt;  lt;property name="hibernate.dialect"gt;org.hibernate.dialect.MySQLDialectlt;/propertygt;  lt;property name="hibernate.show_sql"gt;truelt;/propertygt;  lt;property name="hibernate.use_sql_comments"gt;truelt;/propertygt;  lt;property name="hibernate.format_sql"gt;truelt;/propertygt;  lt;property name="hibernate.hbm2ddl.auto"gt;createlt;/propertygt;  lt;mapping class="entities.UserEntity"/gt;  lt;/session-factorygt; lt;/hibernate-configurationgt;  

Комментарии:

1. Это может быть потому, что ваши версии Джерси не совпадают. Вы используете 1.19.2 для jersey-bundle , jersey-server , и jersey-core , но 1.8 для jersey-json .

2. Я проверил, но, похоже, это не так

3. Вы получаете такое же исключение?