英文:
Creating POJO and returning multiple object values
问题
我正在从以下格式的JSON中读取:
{
"student" : [
{
"roll" : 1,
"name" : "abc",
"subjects" : [
{
"major" : "chemistry",
"minor" : "maths"
},
{
"major" : "biology",
"minor" : "physics"
}
]
},
{
"roll" : 2,
"name" : "xyz",
"subjects" : [
{
"major" : "english",
"minor" : "biology"
},
{
"major" : "english",
"minor" : "physics"
}
]
}
]
}
我将 "student" 存储为一个字符串,并将每个学生的详细信息 - 'roll, name, subjects' 存储为一个POJO。
- 使用以下代码可以将 JSON 转换为对象:
ObjectMapper mapper = new ObjectMapper();
Map<String, List<POJO>> object = mapper.readValue(Json, new TypeReference<Map<String,List<POJO>>>(){});
- 要返回特定学生的所有主修和辅修课程,可以考虑使用一个Map。使用学生的名字作为键,将主修和辅修课程作为值存储在一个Map中,这样可以方便地进行查询。例如:
Map<String, List<Map<String, String>>> studentCourses = new HashMap<>();
然后,将每个学生的主修和辅修课程列表存储在这个Map中。这样,当你想要返回特定学生的主修和辅修课程时,只需通过学生的名字在Map中查找对应的课程列表即可。
这是翻译好的内容,不包含其他额外内容。
英文:
I am reading from a JSON of the format :
{
"student" : [
{
"roll" : 1,
"name" : "abc",
"subjects" : [
{
"major" : "chemistry",
"minor" : "maths"
},
{
"major" : "biology",
"minor" : "physics"
}
]
},
{
"roll" : 2,
"name" : "xyz",
"subjects" : [
{
"major" : "english",
"minor" : "biology"
},
{
"major" : "english",
"minor" : "physics"
}
]
}
]
}
I am storing "student" to a string and making each student details - 'roll, name, subjects' into a POJO.
-
ObjectMapper mapper = new ObjectMapper(); <br />Map<String, List<POJO> object = mapper.readValue(Json, ?);
<br />When I give 'Map.class', I get error and when I give new TypeReference<Map<String,List<RevisionedTenantQuery>>>(){}, it stores the package, not json to POJO. What do I give in place of '?' -
What is the best way to return all the major and minor of a particular student given the student name? Should I do a hashmap or list? Or is there any other way?
答案1
得分: 1
我假设你正在读取JSON字符串,并且需要将它们转换为POJO。在这种情况下,你需要按照以下方式设计你的POJO类:
class Reports {
private final List<Student> student;
// getters & setters
}
class Student {
private final int roll;
private final String name;
private final List<Subject> subjects;
// getters & setters
}
class Subject {
private final String major;
private final String minor;
// getters & setters
}
然后你可以像下面这样使用:
ObjectMapper mapper = new ObjectMapper();
Reports reports = mapper.readValue(jsonString, Reports.class);
英文:
I am assuming that you are reading JSON string, and you need to convert them into POJO, in that case you need to design you POJO as below,
class Reports{
private final List<Student> student;
// getters & setters
}
class Student {
private final int roll;
private final String name;
private final List<Subject> subjects;
// getters & setters
}
class Subject{
private final String major;
private final String minor;
// getters & setters
}
Then you can use as below,
ObjectMapper mapper = new ObjectMapper();
Reports reports = mapper.readValue(jsonString, Reports.class);
POST Edited
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论