0

this may be a stupid question, but I couldn't find a clear answer on the web. I'm building a REST api with javax.ws.rs. I've got a class that looks like this

public class Person{

    private String name;

    private List<Telephone> telephones;

    constructor + getters + setters
}

I'm implementing a getAllPerson REST call that should return json. This is what I'm doing right now:

Path("/persons")
@GET
@Produces({MediaType.APPLICATION_JSON})
public List<Person> getAllPersons() {
    return facade.getAllPersons();
}

I don't think this is the right way to do it, because it gives me an error (HTTP Status 500 - Internal Server Error...)

And I also have no idea how the program would know how to convert a list of person objects that contains another list of telephone objects to JSON.

So what is the right way to return a list like that in JSON, should I manually build the json String? And what should the return type of the getAllPersons() be?

Sorry if this is a really stupid question, but I couldn't find an answer that was clear to me. Thanks in advance.

EDIT: The error I got is:

Severe:   MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<com.myproject.domain.Person>.

EDIT2: I've added @XmlRootElement to my Person class and I added an empty constructor

I also added this to my pom file:

<dependency>
     <groupId>com.fasterxml.jackson.jaxrs</groupId>
     <artifactId>jackson-jaxrs-json-provider</artifactId>
     <version>2.6.4</version>
 </dependency>
Bosiwow
  • 2,025
  • 3
  • 28
  • 46

1 Answers1

-1

As you rightly guessed, you are getting a internal error as you are not returning a JSON. You need to create and return a JSON object with the necessary data. You can create a JSON in Java by two ways:

  • Use JSON Object
  • Serialize a class into JSON Object

A sample way of creating JSON Object is:

import org.json.simple.JSONObject;
JSONObject sampleJSON= new JSONObject();
sampleJSON.put("name", "Hello");
sampleJSON.put("age", 23);

To return the JSON object use:

Path("/persons")
@GET
@Produces({MediaType.APPLICATION_JSON})
public JSONObject returnJSONData() {
    JSONObject sampleJSON= new JSONObject();
    sampleJSON.put("name", "Hello");
    sampleJSON.put("age", 23);
    return sampleJSON;
}
codingsplash
  • 4,785
  • 12
  • 51
  • 90
  • Isn't there an automatic way to convert from Java objects to json? – Bosiwow Dec 11 '15 at 10:34
  • Yes, using a library like Jackson. For an example see here: http://www.studytrails.com/java/json/jackson-create-json.jsp – codingsplash Dec 11 '15 at 10:36
  • 1
    :o, Think I got it working: http://www.tutorialspoint.com/jackson/jackson_tutorial.pdf was a better tutorial for me, thanks for the help :) – Bosiwow Dec 11 '15 at 10:47