Click here to Skip to main content
15,893,190 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello every one,
I have an Employee class :

import java.util.List;
public class Employee {
    private String name;
    private String profession;
    private Integer profId;
    private List<String> roles;

    public String getName() {
        return name;
    }

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

    public String getProfession() {
        return profession;
    }

    public void setProfession(String profession) {
        this.profession = profession;
    }

    public Integer getProfId() {
        return profId;
    }

    public void setProfId(Integer profId) {
        this.profId = profId;
    }

    public List<String> getRoles() {
        return roles;
    }

    public void setRoles(List<String> roles) {
        this.roles = roles;
    }

    @Override
    public String toString() {
        String result = name + "\n" + profession + "\n"
                + profId + "\n" + roles.toString();

        return result;
    }

}


I try to generate a Json representation for a list of employees :

List<Employee> emps = new ArrayList<>();
Employee emp1 = new Employee(){
            {
                setName("Hassan");
                setProfession("doctor");
                setProfId(52);
                setRoles( Arrays.asList("surgeon" ,  "nose"));
            }};

        Employee emp2 = new Employee(){
            {
                setName("Jack");
                setProfession("Developer");
                setProfId(52);
                setRoles( Arrays.asList("Java" ));
            }};

        Employee emp3 = new Employee(){
            {
                setName("Safy");
                setProfession("Driver");
                setProfId(52);
                setRoles( Arrays.asList("Nice" , "Kind" ));
            }};

        emps.add(emp1);
        emps.add(emp2);
        emps.add(emp3);
Gson gson = new Gson();
Type type = new TypeToken<List<Employee>>(){}.getType();
String jsonString = gson.toJson(emps,type);



The resulting jsonString = "[null,null,null]"

in debug the emps List has the 3 employees as expected and none of them is null

How can this be properly done ?

Thanks very much!

What I have tried:

I searched,
all the answers said I should just use the TypeToken in declaring the type witch I did but with no result,
Posted
Updated 30-Nov-17 10:24am

1 solution

Remove the double brace initializations, see here: What is Double Brace initialization in Java? - Stack Overflow[^].
 
Share this answer
 
Comments
Ahmad_kelany 30-Nov-17 16:49pm    
Thanks very much!
You're a life saver :)
CPallini 1-Dec-17 3:04am    
You are welcome.
That was an interesting problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900