[英]How do I parse the below JSON with Jackson. What is the most relevant java object to create for using Jackson ObjectMapper?
Assuming I have a JSON response like this: 假设我有这样的JSON响应:
[{
"employees" : [{
"name" : "Peter",
"dob" : "19850101"
}, {
"name" : "Mark",
"dob" : "19850202"
}, {
"name" : "Steve",
"dob" : "19850303"
}
],
"projects" : [{
"reference" : "P1",
"name" : "Project One",
}, {
"reference" : "P2",
"name" : "Project Two",
}, {
"reference" : "P3",
"name" : "Project Three",
}
],
"projectMembers" : [{
"project" : {
"reference" : "P1"
},
"employees" : [{
"name" : "Peter",
"dob" : "19850101"
}, {
"name" : "Steve",
"dob" : "19850303"
}
]
}, {
"project" : {
"reference" : "P2"
},
"employees" : [{
"name" : "Peter",
"dob" : "19850101"
}, {
"name" : "Mark",
"dob" : "19850101"
}, {
"name" : "Steve",
"dob" : "19850303"
}
]
},
]
}
]
How do I parse this JSON with Jackson. 我如何用杰克逊解析这个JSON。 What is the most relevant java object to create for using the Jackson ObjectMapper?
使用Jackson ObjectMapper创建的最相关的java对象是什么? Or this should be handled using any custom deserializer?
或者这应该使用任何自定义反序列化器来处理?
In my Opinion you will need two basic DTOs. 在我的意见中,您将需要两个基本的DTO。 One for the elements refering to the Projects, which will have two fields (reference and name, both as Strings) and one for the Employees, which will also have two fields (name (String) and dob (Long)).
一个用于引用Projects的元素,它们有两个字段(引用和名称,都是字符串)和一个Employees,它们也有两个字段(name(String)和dob(Long))。 Then you will need an extra Class to handle the combination of a Project to multiple employees (this class has two fields: one Project and a List of Employees).
然后,您将需要一个额外的类来处理项目与多个员工的组合(此类有两个字段:一个项目和一个员工列表)。 To be able to parse the JSON you will then have to create a DTO wrapping your JSON.
为了能够解析JSON,您必须创建一个包装JSON的DTO。 This Class will have three fields one list of employees, one list of projects and one list of the class assigning employees to projects.
该类将有三个字段,一个是员工列表,一个是项目列表,另一个是将员工分配给项目的列表。
For example something like this: 例如这样的事情:
public class Employee{
private String name;
private Long dob;
//default constructor and getter/setter
}
public class Project{
private String reference;
private String name;
//default constructor and getter/setter
}
public class EmployeesToProject{
private Project project;
private List<Employee>;
//default constructor and getter/setter
}
public class CompleteJSON{
private List<Employee> employees;
private List<Project> projects;
private List<EmployeesToProject> projectMembers;
//default constructor and getter/setter
}
You can then parse your JSON with the CompleteJSON-Class 然后,您可以使用CompleteJSON-Class解析JSON
You should rename the DTOs to something more readable 您应该将DTO重命名为更具可读性的东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.