有点不清楚您在问什么,因为您的示例输出不是有效的 JSON。我在这里假设您希望将员工标识符映射到员工列表,您可以使用Map<Integer, List<Employee>> 对其进行建模。要从此数据结构生成 JSON,您需要一个外部库,例如 Jackson JSON 库。
假设以下Employee类
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;
}
}
和编组代码
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);
你会得到这个 JSON:
{
“102”:[{
“身份证”:102,
“名称1”:“D”,
"name2" : "Forouzan",
“名称3”:“麦克”
}, {
“身份证”:102,
“name1”:“操作”,
"name2" : "嘎",
“名称3”:“Wi”
}],
“101”:[{
“身份证”:101,
"name1" : "哈",
"name2" : "德",
“名称3”:“Acr”
}, {
“身份证”:101,
"name1" : "YUI",
"name2" : "你好",
“名称3”:“前”
}]
}
代码所需的 Maven 依赖项:
<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>