0

I got the following function in my REST Java service running in a Glassfish Server:

serviceTest.java

@Path("/servicetest")
public class serviceTest{
    @GET
    @Path("/findall")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> findAll(){
        List <Person> result = new ArrayList<>();
        result.add(new Person("1", "Charlie");
        result.add(new Person("2", "Mary");
        return result;
        }
    }

Also I have defined a class:

person.java

public class person {

    private String id;
    private String name;

    public person(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

When I called the findAll() function from the client side or a web browser, I'm getting the following JSON object in this format:

[
    {
        "id": "1",
        "name": "Charlie"    
    },

    {
        "id": "2",
        "name": "Mary"  
    }
]

But I need to identify the JSON array by a name, something like this:

{"person":
    [
        {
            "id": "1",
            "name": "Charlie"    
        },

        {
            "id": "2",
            "name": "Mary"  
        }
    ]
}

How can I do this...? Thanks in advance...

2 Answers 2

2

You can wrap the person list in a map:

public Map<String,List<Person>> findAll(){
    List <Person> list = new ArrayList<>();
    list.add(new Person("1", "Charlie");
    list.add(new Person("2", "Mary");
    LinkedHashMap<String,List<Person>> map = new LinkedHashMap<>();
    map.put("person", list);
    return map;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, but now I'm getting this error: HTTP Status 500 - Internal Server Error. The server encountered an internal error that prevented it from fulfilling this request.
@CyborgNinja23 search the log files for a stack trace
1

Wrap the List<Person> in a class with a single field:

public class PersonResponse {

    private List<Person> person = new ArrayList<Person>();

    public PersonResponse(List<Person> person) {
        this.person = person;
    }

}

And change your REST method to:

public PersonResponse findAll(){
    List <Person> result = new ArrayList<>();
    result.add(new Person("1", "Charlie");
    result.add(new Person("2", "Mary");
    return new PersonResponse(result);
    }
}

1 Comment

For some reason, when I wrap it in this class, it gives me the 'Status 500 - Internal Server Error'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.