我想拆分一个 json 文件并将其内容存储在一个数组中,然后将它们打印到控制台,除了将 List 转换为字符串数组的问题之外,我已经成功地这样做了。
我的代码是:
package com.acme.datatypes;
公共类用户{
private List<String> authors;
private String publisher;
private String title;
private int year;
public List<String> getAuthors() {
return this.authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public String getPublisher() {
return this.publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return this.year;
}
public void setYear(int year) {
this.year = year;
}
}
和另一个类:
package com.acme.datatypes;
公共类用户测试 {
public static void main(String[] args) throws JsonParseException,
JsonMappingException, IOException {
split("");
}
// Parsing or Reading the JSON file using external libraries
public static String split(String V) throws JsonParseException,
JsonMappingException, IOException {
File jsonFile = new File("library.json");
ObjectMapper mapper = new ObjectMapper();
List<User> userList = mapper.readValue(jsonFile,
new TypeReference<List<User>>() {
});
// Store the titles in an array and then print them out to the
// console
for (User usert : userList) {
String[] title = new String[1];
for (int c = 0; c < 1; c++) {
title[c] = usert.getTitle();
System.out.println(title[c]);
}
}
// Create blank line on console
System.out.println();
// Store the publishers in an array and then print them out to the
// console
for (User userp : userList) {
String[] publisher = new String[1];
for (int i = 0; i < 1; i++) {
publisher[i] = userp.getPublisher();
System.out.println(publisher[i]);
}
}
// Create blank line on console
System.out.println();
// Store the year(for a book) in an array and then print them out to the
// console
for (User usery : userList) {
int[] year = new int[1];
for (int j = 0; j < 1; j++) {
year[j] = usery.getYear();
System.out.println(year[j]);
}
}
// Create blank line on console
System.out.println();
;
return V;
}
}
}
My json file is :
[
{
"title": "Principles of Compiler Design",
"authors": [
"Aho",
"Ullman"
],
"publisher": "Addison Wesley",
"year": 1977
},
{
"title": "Compilers: Principles Techniques and Tools",
"authors": [
"Aho",
"Sethi",
"Ullman"
],
"publisher": "Addison Wesley",
"year": 1985
}]