ChrisGeo
ChrisGeo

Reputation: 3907

JAX-RS Auto marshalling List<Object> to JSON

I am using Glassfish 3 which uses the Jersey Implementation for JAX-RS. I have the following method REST endpoint:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<CourseDTO> listAll() {

    List<CourseDTO> list = findAll();


    return list;
}

My CourseDTO is the following:

@XmlRootElement
public class CourseDTO implements Serializable {


    private long courseId;
    private String courseName;


    public CourseDTO() {

    }
     //getters setters
}

The JSON object I get back is the following:

  {
      "courseDTO":
           [
              {"courseId":"1","courseName":"C++"},
              {"courseId":"2","courseName":"Java"}
           ]
   }

However, ideally I would want the following:

[
    {"courseId":"1","courseName":"C++"},
    {"courseId":"2","courseName":"Java"}
]

So basically I want to get rid of the "wrapper" object. Is there someway to do it or should I have to do manual marshalling?

Upvotes: 0

Views: 798

Answers (1)

shahshi15
shahshi15

Reputation: 2987

Try using Google Gson library. The code is as simple as :

Type listType = new TypeToken<ArrayList<CourseDTO >>() {
                    }.getType();
 List<CourseDTO > courses = new Gson().fromJson(jsonArray, listType);

Upvotes: 1

Related Questions