Ben
Ben

Reputation: 62404

How to return data via json

I'm trying to return information about guests (only an id and name right now) but I can't figure out how to properly do it. My method is below

How can I sent only the id and name to myData.put() since java doesn't accept associative arrays? I've tried creating a class within this method to be returned but that turns out to be illegal in java as well. What's the idea solution here?

/**
 * Retrieves representation of an instance of contentmanagement.ContentManagement
 * @return an instance of java.lang.String
 */
@GET @Path("getHtml")
@Produces("application/json")
public String getGuests() {
    JSONArray myData = new JSONArray();

    for(Guest item : guestDao.getAllGuests()) {
        myData.put({});
    }

    return myData.toString();
}

Upvotes: 2

Views: 237

Answers (1)

Allen Z.
Allen Z.

Reputation: 1588

The JSONObject class represents the name-value pair, so your code looks like:

/**
 * Retrieves representation of an instance of contentmanagement.ContentManagement
 * @return an instance of java.lang.String
 */
@GET @Path("getHtml")
@Produces("application/json")
public String getGuests() {
    JSONArray myData = new JSONArray();

    for(Guest item : guestDao.getAllGuests()) {
        myData.put(new JSONObject().put("id", item.getID())
          .put("name", item.getName()));
    } 

    return myData.toString();
}

Upvotes: 1

Related Questions