我正在尝试解析此json文件(在代码中对其进行定义),然后计算特定单词出现的频率,例如“草食动物”。 但是除了缺少任何字符外,我每次都会得到“ 0”。 “”,这表示控制台编号13。此外,我不确定是否正确解析了文件
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.simple.JsonArray;
import org.json.simple.JsonObject;
import org.json.simple.Jsoner;
public class JSONSerializeDeserialize {
public JSONSerializeDeserialize() {
//Create the JSON file
System.out.println("Creating JSON file...\n");
createJSON();
System.out.println("Created...");
//Read the JSON file
System.out.println("Reading JSON file...\n");
readJSON();
System.out.println("Finished Reading JSON File...\n");
//Finally
System.out.println("Application finished...");
}
public void readJSON(){
String jsonFilePath = "animals.json";
int i=0;
Pattern p = Pattern.compile("h");
Matcher m = p.matcher(jsonFilePath);
while (m.find()) {
i++;
}
System.out.println(i);
try(FileReader fileReader = new FileReader(jsonFilePath)){
JsonObject json = (JsonObject) Jsoner.deserialize(fileReader);
JsonArray animals = (JsonArray) json.get("animals");
System.out.println("\nAnimals are :");
animals.forEach(animal -> {
JsonObject animalObject = (JsonObject) animal;
System.out.println("Weight : " + animalObject.getString("weight")+", Growth : " + animalObject.get("growth")+", Type of : " + animalObject.get("typeof"));
});
} catch (Exception ex){
ex.printStackTrace();
}
}
public void createJSON(){
String jsonFilePath = "animals.json";
JsonObject json = new JsonObject();
JsonArray animals = new JsonArray();
JsonObject animalA = new JsonObject();
animalA.put("weight", "light");
animalA.put("growth", "small");
animalA.put("typeof", "herbivore");
JsonObject animalB = new JsonObject();
animalB.put("weight", "medium");
animalB.put("growth", "short");
animalB.put("typeof", "carnivorous");
JsonObject animalC = new JsonObject();
animalC.put("weight", "heavy");
animalC.put("growth", "high");
animalC.put("typeof", "omnivorous");
JsonObject animalD = new JsonObject();
animalD.put("weight", "heavy");
animalD.put("growth", "high");
animalD.put("typeof", "omnivorous");
animals.add(animalA);
animals.add(animalB);
animals.add(animalC);
animals.add(animalD);
json.put("animals", animals);
try (FileWriter file = new FileWriter(jsonFilePath)){
file.write(Jsoner.prettyPrint(json.toJson()));
file.flush();
} catch (IOException e){
e.printStackTrace();
}
}
public static void main (String[] args){
new JSONSerializeDeserialize();
}
}