It is a bit unclear what you're asking because your example output isn't valid JSON. I am assuming here that you'd want to map employee identifiers to lists of employees, which you can model with a Map<Integer, List<Employee>>
. To produce JSON from this data structure, you need an external library, such as Jackson JSON library.
Assuming the following Employee
class
public class Employee {
private final int id;
private final String name1;
private final String name2;
private final String name3;
public Employee(int id, String name1, String name2, String name3) {
this.id = id;
this.name1 = name1;
this.name2 = name2;
this.name3 = name3;
}
public int getId() {
return id;
}
public String getName1() {
return name1;
}
public String getName2() {
return name2;
}
public String getName3() {
return name3;
}
}
And marshaling code
Employee e1 = new Employee(101,"Ha","De","Acr");
Employee e2 = new Employee(102,"D ","Forouzan","Mc");
Employee e3 = new Employee(102,"Op","Ga","Wi");
Employee e4 = new Employee(101,"YUI","HI","EX");
Map<Integer, List<Employee>> employees = new HashMap<>();
employees.put(101, Arrays.asList(e1, e4));
employees.put(102, Arrays.asList(e2, e3));
String json = new ObjectMapper().writerWithDefaultPrettyPrinter()
.writeValueAsString(employees);
System.out.println(json);
you'll get this JSON:
{
"102" : [ {
"id" : 102,
"name1" : "D ",
"name2" : "Forouzan",
"name3" : "Mc"
}, {
"id" : 102,
"name1" : "Op",
"name2" : "Ga",
"name3" : "Wi"
} ],
"101" : [ {
"id" : 101,
"name1" : "Ha",
"name2" : "De",
"name3" : "Acr"
}, {
"id" : 101,
"name1" : "YUI",
"name2" : "HI",
"name3" : "EX"
} ]
}
Required Maven dependencies for the code:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<!-- Jackson databinding; ObjectMapper, JsonNode and related classes are here -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>