I have written a jersey REST API method which returns a list of persons which is queried from mysql backend using hibernate. Here is the method
@Path("Person")
@GET
@Produces(MediaType.TEXT_PLAIN)
public List<Person> person()
{
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Criteria cr = session.createCriteria(Person.class);
List persons = cr.list();
GenericEntity<List<Person>> list = new GenericEntity<List<Person>>(persons) {};
tx.commit();
session.close();
return persons;
}
and here is my MessageBodyWriter
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class PersonMessageBodyWriter implements MessageBodyWriter<Person> {
@Override
public long getSize(Person arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
// TODO Auto-generated method stub
return -1;
}
@Override
public boolean isWriteable(Class<?> type, Type arg1, Annotation[] arg2, MediaType arg3) {
return Person.class.isAssignableFrom(type);
}
@Override
public void writeTo(Person person, Class<?> type, Type type1, Annotation[] arg3, MediaType arg4,
MultivaluedMap<String, Object> arg5, OutputStream out) throws IOException, WebApplicationException {
// TODO Auto-generated method stub
out.write(person.toString().getBytes());
}
}
When i make a get request to the above method i am getting SEVERE: MessageBodyWriter not found for media type=text/plain, type=class java.util.ArrayList, genericType=java.util.List. can someone please help me get through with this problem?
What I've always done in this case is make a Persons object that contains the List of persons. There may be a better way but if your under a time crunch and want to get it done then this should work. If it doesn't work then my guess that no JSON marshalling is working, in which case you have a configuration problem.
import java.util.ArrayList;
import java.util.List;
public class Persons
{
private List<Person> persons = new ArrayList<>();
public List<Person> getPersons()
{
return persons;
}
public void setPersons(List<Person> persons)
{
this.persons = persons;
}
}
I understand that this is quite an old question - However, there is an excellent solution to this now. Whenever you wish to return a list of objects, you can utilise the below code:
List<KaggleFileResponse> data = kaggleService.listFiles(xxxx);
GenericEntity<List<KaggleFileResponse>> entity = new GenericEntity<List<KaggleFileResponse>>(data) {};
return Response.status(HttpStatus.SC_OK).entity(entity).build();
The code converts the list into a generic entity that can be written back.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.