[英]parse json file recursively with JAVA
我有一個包含章節和子章節的 json 文件......它的章節和子章節的數量並不總是相同:例如
{
"IDCours" : "CS10.44",
"title": " .... ",
"chapters": [
{
"idChapter": "1",
"title": "Introduction",
"chapters": [
{
"idChapter": "1.1",
"title": "basics",
"content" : " blab bla blab "
},
{
"idChapter": "1.2",
"title": "basics",
"content" : " blab bla blab "
}
]
},
{
"idChapter": "2",
"title": "..... ",
"chapters": [
{
"idChapter": "2.1",
"title": " .... ",
"content" : " blab bla blab "
},
{
"idChapter": "2.2",
"title": ".....",
"content" : " blab bla blab ",
"chapters": [
{
"idChapter": "2.2.1",
"title": " .... ",
"content" : " blab bla blab "
}
]
}
]
}
]
}
所以,我認為應該遞歸完成,因為我事先不知道文件中有多少章節和子章節,子子章節
你不需要遞歸地做。 我通常使用 jackson 庫來處理 Json 的庫,所以這里是如何完成的。
public class mainClass {
String IDCours;
String title;
List<Chapters> chapters;
public static class Chapters {
double idChapter;
String title;
List<InnerChapters> chapters;
@JsonIgnoreProperties(ignoreUnknown = true)
public static class InnerChapters {
double idChapter;
String title;
String content;
List<InnerChapters> chapters;
}
}
}
並使用方法來解析您的 json,例如:
public static final ObjectMapper objMapper;
static {
objMapper= new ObjectMapper();
objMapper.registerModule(new JavaTimeModule());
}
public static <T> List<T> fromJsonToList(String json, Class<T> clazz) throws IOException {
CollectionType customClassCollection = MAPPER.getTypeFactory().constructCollectionType(List.class, clazz);
return objMapper.readValue(json, customClassCollection);
}
如果沒有章節列表並繼續解析您的 json,@JsonIgnoreProperties 注釋將忽略並且不會拋出異常。 嘗試一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.