Java Jersey - Returning JSON with labels

Hi,

I've just started learning how to build API's in Java after many years of using PHP.

At first I struggled with returning multiple objects, but I've figures that putting each object into a ArrayList resolves this. The problem I have is that I would like to label each JSON object.

As an example, in PHP...
$response['categories'] = $categoryRepo->all();
$response['exercises'] = $exerciseRepo->all();
echo json_encode($response);

Open in new window


The above would return both lists of objects each labelled as 'categories' and 'exercises'.

In Java so far I'm doing this...
class Response getAll() {
     ArrayList response = new ArrayList<>();

     ArrayList.add(CategoryRepository.all());
     ArrayList.add(ExerciseRepository.all());

     return Response.ok(response).build();
}

Open in new window


This returns a list of both objects, but there's no way looking at the JSON that you can tell which list of objects is which. How would I go about doing this?
SheppardDigitalAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
Instead of a List try using a Map. A Map is closer to the PHP associative array that you posted.

class Response getAll() {
     Map <String, Object> response = new HashMap<>();

     response.put("categories", CategoryRepository.all());
     response.put("exercises", ExerciseRepository.all());

     return Response.ok(response).build();
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SheppardDigitalAuthor Commented:
That is perfect, thank you.
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
You're welcome!!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.