Jackson ObjectMapper JSON для объекта Java ВОЗВРАЩАЕТ НУЛЕВЫЕ значения

#java #json

#Ява #json

Вопрос:

Я пытаюсь перебрать дочерний объект массива JSON, в котором хранятся объекты. Мой файл JSON выглядит следующим образом:

 { "species": [  {  "sourcebook": "Revised Core Rulebook",  "file": "src/main/resources/db/core_rulebook/species/human.md",  "name": "Human",  "description": "Humans dominate the Core Worlds and can be found in virtually every corner of the galaxy. They are the ancestors of early spacefaring pioneers, conquerors, traders, travelers and refugees. Humans have always been people on the move. As a result, they can be found on almost every inhabitable planet. As a species, Humans as physically, culturally, and politically diverse. Hardy or fine, light-skinned or dark, Humans remain one the most dominant species throughout all eras of play.",  "personality": "Human personality runs the gamut of possibilities, though member of this species tend to be highly adaptable, tenacious, and willing to keep striving no matter the odds. They are flexible and ambitious, diverse in their tastes, morals, customs, and habits.",  "appearance": "Humans average about 1.8 meters tall. Skin shades run from nearly black to very pale., hair from black to blond. Men are usually taller and heavier than the women. Humans achieve maturity about the age of 15 and rarely live beyond 100.",  "homeworld": "Various, including Coruscant, Corulag, Naboo, Tatooine, and Alderaan.",  "language": "Humans speak and read Basic. They typically learn other languages, including obscure ones.",  "adventurers": "Humans aren't afraid to try anything, and Human adventurers are the most audacious, daring, and ambitious species. A Human can earn glory by amassing power, wealth, and fame. More than another species, Humans champion cause rather than territories or groups.",  "spoken_language": [  "Basic"  ],  "literate_language": [  "Basic"  ],  "abilities": [  0,  0,  0,  0,  0,  0  ],  "size": "Medium",  "speed": 10  },  {  "sourcebook": "Revised Core Rulebook",  "file": "src/main/resources/db/core_rulebook/species/bothan.md",  "name": "Bothan",  "description": "The planet Bothawui, in the Mid Rim of the galaxy, gave rise to the Bothan species. These shoprt, fur-covered humaniods have had hyperspace travel for thousands of years and were among the first civilizations to join the galactic society. Bothans deal in information. They use information as a measure of wealth and power, even wielding it as a weapon when necessary. The Bothan Spynet serves as one of the largest intelligence agencies throughout most eras, and it plays and important and poignant role in the Rebellion era. Culturally, Bothans don't believe in direct conflict. They prefer to manipulate situations from behind the scenes, to watch and wait for information and opportunity, and to use these tools to gain status and influence.",  "personality": "Bothans are manipulative, crafty, suspicious and curious by anture, and a little paranoid. They can be irritating, but they are also loyal and brave.",  "appearance": "Bothans are covered with fur that ripples in response to their emotional state. They have tappered ears, and both male and female Bothans sport beards. They average about 1.6 meters tall and have a maturity rate and life span slightly greater than Humans.",  "homeworld": "The industrial world of Bothawui, with various colony worlds throughout the Mid Rim Territories, including Kothlis and Torolis.",  "language": "Bothans speak and read Bothese and Basic.",  "adventurers": "Bothan adventurers, such as operatives in the Spynet, engage in daring deeds - even when such deeds put them at great personal risk. In addition to the intelligence operatives, Bothan heroes serve as soldiers and pilots, diplomats and ambassadors. Their curiosity leads some to be explorer and scouts. Even when a Bothan makes it hard not to look for the profit and prestige in the situation.",  "spoken_language": [  "Basic",  "Bothese"  ],  "literate_language": [  "Basic",  "Bothese"  ],  "abilities": [  0,  2,  -2,  0,  0,  0  ],  "size": "Medium",  "speed": 10  },  {  "sourcebook": "Revised Core Rulebook",  "file": "src/main/resources/db/core_rulebook/species/cerean.md",  "name": "Cerean",  "description": "Cereans come from a remote utopian world. Most Cereans are peaceful, following farming traditions that date back thousands of years. The species includes more females than males, and Cerean society is matriarchal. Their high-domed heads hold binary brians, and two hearts beat in a Cerean's chest. With a non-aggressive heritage, it is only rarely that a Cerean develops the desire to adventure, and even more rare that one takes up the robes of a Jedi Knight.",  "personality": "Cereans tend to be calm, rational, and extremely logical.",  "appearance": "Cereans average about two meters tall, with elongated craniums. They have a maturity rate and life span similar to that of Humans.",  "homeworld": "The blissful planet Cerea.",  "language": "Cereans speak and read Cerean and Basic.",  "adventurers": "Cereans who become adventurers do so in direct contradiction to their traditions and beliefs. Even so, when a cause or situation turns a Cerean to this path, he or she tries to approach life with as many of the Cerena beliefs as possible. Aggression should be the last resort after all peaceful solutions are attempted, for example. The binary brain allows a Cerean to constantly weigh both sides in an disagreement and give two points of view equal consideration. This ability extends even to issues surrounding the Force, and a Cerean Force-user often contemplates the light and dark side simultaneously.",  "spoken_language": [  "Basic",  "Cerean"  ],  "literate_language": [  "Basic",  "Cerean"  ],  "abilities": [  0,  -2,  0,  2,  2,  0  ],  "size": "Medium",  "speed": 10  },  {  "sourcebook": "Revised Core Rulebook",  "file": "src/main/resources/db/core_rulebook/species/Duros.md",  "name": "Duros",  "description": "The Duros originate in the Duro star system, located at the extreme edge of the Core region of space. With an almost innate affinity for space travel, the Duros were among the first to leave their world and spread to the stars. Whatever the reason for their wanderlust, the Duros tend to gravitate toward the space lanes for income and adventure. Their home system is governed by vast starship engineering corporations, and most Duros learn to pilot a ship or rebuild a hyperdrive shortly after they begin to walk and talk.",  "personality": "A Duros tends to be intense and adventureous, always seeking to learn what's at the end of the next hyperspce jump. They are a proud, self-sufficient, fun-loving people who also have a tendency toward gregariousness.",  "appearance": "Duros average about 1.8 meters tall. They are hairless, with large eyes and wide, lipless mouths. Skin color ranges from blue-gray to deep azure.",  "homeworld": "The orbiting cities of the Duro system.",  "language": "Duros speak and are literate in Durese and Basic.",  "adventurers": "Duros adventurers include hyperspace explorers, star charter and spaceer of all descriptions. They also tend to gravitate toward the sciences, including engineering and astrogation. Some Duros shun exploration in favor of smuggling and trading, and a small number go into diplomatic professions.",  "spoken_language": [  "Basic",  "Durese"  ],  "literate_language": [  "Basic",  "Durese"  ],  "abilities": [  -2,  2,  -2,  2,  0,  0  ],  "size": "Medium",  "speed": 10  },  {  "sourcebook": "Revised Core Rulebook",  "file": "src/main/resources/db/core_rulebook/species/Ewok.md",  "name": "Ewok",  "description": "Ewoks hail from the forest moon of Endor, where they maintain a primitive hunter/gather society. Prior to the Battle of Endor (four year after Episode IV), Ewoks were almost entirely unknown to the galaxy at large. Som traders and explorer visited Endor's moon, but with no form of space travel, Ewoks never left their homeworld. Although primitive by galactic standards, the tribal Ewoks are resourceful and highly adaptable. The tribal Ewoks may be technologically primitive when compared to most of the galactic society, but they are also clever and inventive. While they tend to initially be wary around machinery, it isn't long before their natural curiosity wins out and they plunge into wild and exuberant experimentation.",  "personality": "Ewoks tend to be curious, superstitious, and courageous, though they can be fearful around things that are strange and new.",  "appearance": "Ewoks average about 1 meter tall. Their thick fur varies widely in color and pattern. They often wear hoods, decorative feather, and animal bones.",  "homeworld": "The forest moon of Endor.",  "language": "Ewoks speak Ewokese. They have no written form of their language. They can learn to speak Basic.",  "adventurers": "An Ewok adventurer may be motivated by a love of excitement, a natural inquisitiveness, or a warrior's quest. Usually, an Ewok hero joins up with a scout or hero who has access to a starship. Collecting powerful "magic" items from fallen opponents, such as a stormtrooper's helmet or a range finder from a blaster rifle, is a sure way for an Ewok to earn the respect of his tribe.",  "spoken_language": [  "Basic",  "Ewokese"  ],  "literate_language": [  "Basic",  "Ewokese"  ],  "abilities": [  -2,  2,  0,  0,  0,  0  ],  "size": "Small: As Small creatures, Ewoks gain a  1 size bonus to the Defense, a  1 size bonus on Attack Rolls, and a  4 size bonus on Hide Checks, but they must use smaller weapons than Humans use, and their lifting and carrying limits are three-quarter of those of Medium-sized characters.",  "speed": 6  },  {  "sourcebook": "Revised Core Rulebook",  "file": "src/main/resources/db/core_rulebook/species/Gamorrean.md",  "name": "Gamorrean",  "description": "Brutish and violent, the porcine Gamorreans come from the Outer Rin world of Gamorr. Green-skinned with piglike snouts, tusks, and small horns, Gamorreans are respected for their great strength and short tempers. The history of Gamorr is marked by an almost constant state of warfare. Males train for and fight wars, while the females farm, hunt, and handle trade. Since their homeworld was discovered, a number of Gamorreans have found their way into the galactic society. The technologically poor homeworld has a savage, primitive culture that resembles the pre-industrial periods that human civilizations experienced more than 25,000 years ago. Even so, the physically imposing Gamorreans make good laborer, bodyguards, and mercenaries. While they prefer primitive melee weapons, they have no problem learning to use powered weapons and even blasters.",  "personality": "Gamorreans are brutish, violent and proud. They respect physical prowess and have no problem facing death against a foe they feel they are on at least equal footing with. They do display fear in the face of obviously superior opponents, however, considering such a display to be prudent and even rational.",  "appearance": "Gamorreans average about 1.8 meters tall, with thick green skin covering powerful muscles. Close-set eyes, a thick snout, tusks, and small horns lend a distinct look to every Gamorrean.",  "homeworld": "The pre-industrial agricultural world of Gamorr.",  "language": "Gamorreans speak Gamorrean. They have no written version of the language. They can learn to understand other languages, but Gamorreans lack the mechanism to speak any tongue but their own.",  "adventurers": "Gamorreans leave their homeworld for a variety of reasons. Some are taken as slaves and later escape or buy out their contracts. Others sell their contracts on the open market, finding employment as bodyguards, mercenaries, and professional soldiers. A Gamorrean is constantly at war, no matter where he or she resides in the galaxy; it's often only a matter of figuring out who the enemy is. Gamorrean heroes tend to selec the fringer or soldier classes. To date, there are no known examples of Gamorrean Force-users.",  "spoken_language": [  "Basic",  "Gamorrean"  ],  "literate_language": [  "Basic",  "Gamorrean"  ],  "abilities": [  2,  -2,  0,  -2,  0,  0  ],  "size": "Medium: As Medium-size creatures, Humans have no special bonuses or penalties due to their size.",  "speed": 10  },  {  "sourcebook": "Revised Core Rulebook",  "file": "src/main/resources/db/core_rulebook/species/Gungan.md",  "name": "Gungan",  "description": "From the watery depths of Naboo, the Gungans are an ancient species with a warlike tradition. Gungans can hold their breath for extended periods, and they live within underwater cities. Their bubble dwellings contain a breathable atmosphere. The most common Gungan race is the Otolla Gungan, characterized by taller, leaner frames and extended eyestalks. The rare Ankura Gungan has recessed eyes, green skin, and a heavier, shorter frame. Except for the physical characteristics, there are no genetic differences between the two Gungan races.Usually distrustful of strangers and slow to accept aid, Gungans are nevertheless brave, strong and confident of their own traditions.",  "personality": "Gungans tend to be inquisitive, cautious and suspicious.",  "appearance": "Gungans range from 1.6 to 2 meters tall, with two eyestalks, floppy ears, and long tongues.",  "homeworld": "Naboo (with colonies on the Ohma-D'un moon).",  "language": "Gungans speak Gungan and Basic.",  "adventurers": "Gungan adventurers have a strong warrior tradition. Many leave the underwater cities to explore the ancient swamps and shorelines. Since the treaty with the Humans of Naboo, some Gungans have taken a larger step into galactic society. These brave individuals are driven by an impulse to explore and regain the warrior spirit of olf. There are no examples of Gungan Jedi as yet, though there have been legends of Force adepts among these people.",  "spoken_language": [  "Basic",  "Gungan"  ],  "literate_language": [  "Basic",  "Gungan"  ],  "abilities": [  0,  0,  2,  0,  -2,  0  ],  "size": "Medium",  "speed": 10  },  {  "sourcebook": "Revised Core Rulebook",  "file": "src/main/resources/db/core_rulebook/species/ithorian.md",  "name": "Ithorian",  "description": "Ithorians come from the jungle world of Ithor or one of its many spaceworthy "herd" ships. Also known as Hammerheads by the galaxy at large, Ithorians are a peaceful people. Ithorians dedicate themselves to ecological endeavors, especially on their homeworld, where they seek to preserve the pastoral beauty of the great tropical jungle - the Mother Jungle. A gentle people, Ithorians have a great love of art. Many travel the galaxy in giant hyperdrive herd ships designed to serve as ecological replicas of the Ithorian homeworld, bringing the beauty of Ithor wherever they go.",  "personality": "Ithorians tend to be calm, peaceful, tranquil, and gentle.",  "appearance": "Ithorians are humanoid, ranging in height from 1.8 to 2.3 meter tall, with long necks that curls forward and end in dome-shaped heads. They have two mouths, one on each side of their neck, producing a stereo effect when they talk.",  "homeworld": "Ithor, or a specific herd ship.",  "language": "Ithorians speak stereophonic Ithorese and Basic.",  "adventurers": "Ithorians tend to concentrate on peaceful professions. They love to meet new beings and see new places. They enjoy negotiating deals and finding peaceful solutions to conflict. They have a spiritual nature tied to their devotion to the Mother Jungle of their homeworld. Often, wanderlust leads them to explore the greater galaxy for a time before they eventually return to Ithor or the herd ship that spawned them.",  "spoken_language": [  "Basic",  "Ithorese"  ],  "literate_language": [  "Basic",  "Ithorese"  ],  "abilities": [  0,  -2,  0,  0,  2,  2  ],  "size": "Medium",  "speed": 10  },  {  "sourcebook": "Revised Core Rulebook",  "file": "src/main/resources/db/core_rulebook/species/keldor.md",  "name": "Kel Dor",  "description": "The Kel Dor originate on the planet Dorin, where they developed in an atmosphere of helium and a gas unique to their world. Consequently, more common atmospheres, including those that consist of oxygen, nitrogen, and carbon dioxide, are deadly to the Kel Dor. Those Kel Dor that operate beyond the confines of their homeworld must wear breath masks and protective goggles. \n The Kel Dor have a long and proud Force tradition, though they have adapted it to the Jedi tradition since joining the Republic over six thousand years ago. Kind-hearted, the Kel Dor nevertheless believe in swift justice.",  "personality": "Even-tempered and kind-hearted, the Kel Dor never turn away a being in need. At the same time, the average Kel Dor believes in quick, simple justice and isn't averse to taking the law into his or her own hands.",  "appearance": "The average Kel Dor stands between 1.4 and 2 meters tall. Their skin ranges in color from peach to deep red. Most have black eyes, though a few are born with silver irises that some believe mark them as strong in the Force.",  "homeworld": "The technological planet of Dorin.",  "language": "The Kel Dor speak Kel Dor and Basic.",  "adventurers": "Kel Dor who decide to brave the dangers of living outside their homeworld tend to be nobles such as diplomats and traders, bounty hunters, and Jedi. Their willingness to help others often mixes with their innate sense of justice, leading many into some form of law enforcement.",  "spoken_language": [  "Basic",  "Kel Dor"  ],  "literate_language": [  "Basic",  "Kel Dor"  ],  "abilities": [  0,  2,  -2,  0,  2,  0  ],  "size": "Medium",  "speed": 10  },  {  "sourcebook": "Revised Core Rulebook",  "file": "src/main/resources/db/core_rulebook/species/moncalamari.md",  "name": "Mon Calamari",  "description": "Soft-spoken but forceful, the Mon Calamari are great starship engineers. They see everything they create as a work of art, not just as a tool or weapon. They are a lawful, organized people who have little tolerance for those who operate outside the status quo. They come from a water-covered world and can breathe both air and water. \n Recognized for their analytical and organizational skills, Mon Calamari also have keen love of flying among the stars. They believe in order and the greater good, sometim,es going so far as to support the good of society over the good of the individual.",  "personality": "Creative, quiet, and inquisitive, the Mon Calamari are dreamers who cherish peace but aren't afraid to wage war for the causes they believe in.",  "appearance": "The average Mon Calamari stands between 1.3 and 1.8 meters tall. They smell of salt and the sea, with high-domed heads, large eyes, and smooth, mottled skin.",  "homeworld": "The watery, technological planet of Mon Calamari.",  "language": "The Mon Calamari speak Mon Calamari and Basic. They tend to learn Quarrenese.",  "adventurers": "Mon Calamari seek their dreams among the stars. They are idealistic and daring, often attaching themselves to cause that seem hopeless or lost right from the start. An individual Mon Calamari has great spirit and an entusiasm that often remains hidden behind a quiet, orderly exterior. They strive to prove that even thinkers and dreamers can br brave and daring when the need arises.",  "spoken_language": [  "Basic",  "Mon Calamari"  ],  "literate_language": [  "Basic",  "Mon Calamari"  ],  "abilities": [  0,  0,  -2,  2,  0,  0  ],  "size": "Medium",  "speed": 10  }  ] }  

Я хотел бы перебрать каждый объект массива JSON и вывести их в окно консоли с помощью:

 System.out.println  

Я могу разобрать с

 ObjectMapper.readValue(source, class);  

Хотя это дает мне весь файл JSON и не считывает дочерние объекты в массиве. Как я могу выполнить цикл по массиву и вывести объекты в массиве.

Вот файл класса:

 package Species;  import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.*;  @JsonIgnoreProperties(ignoreUnknown = true)  public class Species {  private String sourcebook;  private String file;  private String name;  private String description;  private String personality;  private String appearance;  private String homeworld;  private String language;  private String adventurers;  private Listlt;Stringgt; spokenLanguage = new ArrayListlt;Stringgt;();  private Listlt;Stringgt; literateLanguage = new ArrayListlt;Stringgt;();  private Listlt;Integergt; abilities = new ArrayListlt;Integergt;();  private String size;  private Integer speed;    public Species() {  // Default Constructor  }   public Species(String sourcebook, String file, String name, String description, String personality, String appearance, String homeworld,  String language, String adventurers, Listlt;Stringgt; spokenLanguage, Listlt;Stringgt; literateLanguage, Listlt;Integergt; abilities, String size, Integer speed) {  this.sourcebook = sourcebook;  this.file = file;  this.name = name;  this.description = description;  this.personality = personality;  this.appearance = appearance;  this.homeworld = homeworld;  this.language = language;  this.adventurers = adventurers;  this.spokenLanguage = spokenLanguage;  this.literateLanguage = literateLanguage;  this.abilities = abilities;  this.size = size;  this.speed = speed;  }   public String getSourcebook() {  return sourcebook;  }  public void setSourcebook(String sourcebook) {  this.sourcebook = sourcebook;  }  public String getFile() {  return file;  }  public void setFile(String file) {  this.file = file;  }  public String getName() {  return name;  }  public void setName(String name) {  this.name = name;  }  public String getDescription() {  return description;  }  public void setDescription(String description) {  this.description = description;  }  public String getPersonality() {  return personality;  }  public void setPersonality(String personality) {  this.personality = personality;  }  public String getAppearance() {  return appearance;  }  public void setAppearance(String appearance) {  this.appearance = appearance;  }  public String getHomeworld() {  return homeworld;  }  public void setHomeworld(String homeworld) {  this.homeworld = homeworld;  }  public String getLanguage() {  return language;  }  public void setLanguage(String language) {  this.language = language;  }  public String getAdventurers() {  return adventurers;  }  public void setAdventurers(String adventurers) {  this.adventurers = adventurers;  }  public Listlt;Stringgt; getSpokenLanguage() {  return spokenLanguage;  }  public void setSpokenLanguage(Listlt;Stringgt; spokenLanguage) {  this.spokenLanguage = spokenLanguage;  }  public Listlt;Stringgt; getLiterateLanguage() {  return literateLanguage;  }  public void setLiterateLanguage(Listlt;Stringgt; literateLanguage) {  this.literateLanguage = literateLanguage;  }  public Listlt;Integergt; getAbilities() {  return abilities;  }  public void setAbilities(Listlt;Integergt; abilities) {  this.abilities = abilities;  }  public String getSize() {  return size;  }  public void setSize(String size) {  this.size = size;  }  public Integer getSpeed() {  return speed;  }  public void setSpeed(Integer speed) {  this.speed = speed;  } }  

Here is main file:

 package Species;  import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.ArrayNode;  import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List;  public class Main {  public static void main(String[] args) {   // File file = new File("src/main/resources/species.json");  File file = new File("src/main/resources/species.1.json");   ObjectMapper mapper = new ObjectMapper();   try {  JsonNode root = mapper.readTree(file);   for(JsonNode species : root) {  // Get Sourcebook  String sourcebook = species.get("sourcebook").toString();  System.out.println(sourcebook);   // Get Species Name  String name = species.get("name").toString();  System.out.println(name);  }   System.out.println(root);   } catch (JsonProcessingException e) {  e.printStackTrace();  } catch (IOException e) {  e.printStackTrace();  }  } }  

Кроме того, я не уверен, правильно ли я это реализую.

Ответ №1:

Вам не хватает класса, соответствующего списку Species , содержащемуся в вашем JSON:

 import java.util.List;  public class SpeciesGroup {  private Listlt;Speciesgt; species;   public Listlt;Speciesgt; getSpecies() {  return species;  }   public void setSpecies(Listlt;Speciesgt; species) {  this.species = species;  } }  

Затем вы можете просто прочитать свой JSON, используя ObjectMapper.readValue() следующий метод:

 import java.io.File; import java.io.FileInputStream; import java.io.IOException;  public class Main {  public static void main(String[] args) {  File file = new File("src/main/resources/species.1.json");   ObjectMapper mapper = new ObjectMapper();  try {  SpeciesGroup speciesGroup = mapper.readValue(new FileInputStream(file), SpeciesGroup.class);  Listlt;Speciesgt; allSpecies = speciesGroup.getSpecies();  allSpecies.forEach(species -gt; {  System.out.println(species.getSourcebook());  System.out.println(species.getName());  });  } catch (IOException e) {  e.printStackTrace();  }  } }  

Комментарии:

1. Прости меня. Я не понимаю, зачем мне понадобился перерыв между занятиями. Кроме того, есть ли способ изменить то, о чем я просил, чтобы создать коллекцию/список объектов для каждого вида?

2. Если вы действительно не хотите пройти трудный путь и использовать JsonNode вместо собственного Species класса для сопоставления JSON, вам нужен другой класс, соответствующий "species" вашему JSON. Вы четко заявили: «Я хотел бы повторить каждый объект массива JSON и вывести их на консоль», и именно это делает мой ответ. speciesGroup.getSpecies() является списком всех видов и forEach() печатает некоторые из их свойств. Если это не то, чего вы хотите, пожалуйста, объясните вашу потребность получше. Спасибо!

3. Я прошу прощения. Вы правы и ответили на вопрос так, как я его задал. Я новичок в изучении Java и не совсем понимаю, как все это сочетается. Спасибо. В комментарии я спрашивал, могу ли я изменить часть, выводимую на консоль, и создать коллекцию/список каждого вида в JSON?

4. Но опять же, это то, что speciesGroup.getSpecies() возвращается к вам. Я отредактировал свой ответ, чтобы сделать это явным. Это то, что вам нужно / чего вы хотите?

5. Поправьте меня, если я ошибаюсь. В Species.class то, что я создал, соответствует только атрибутам объектов видов внутри массива видов в файле JSON. Класс, который вы предлагаете создать, соответствует массиву видов в файле JSON. Без этого дополнительного класса способ, которым я спрашивал Джексона, не знает, что такое массив видов в файле JSON?

Ответ №2:

mapper.readTree(файл) содержит содержимое json всех подобных строк.

 {  json }  

Если вы хотите получить доступ к содержимому видов, вам нужно перейти в дочерний узел, который является видом.Вы объявляете «виды», как под строкой.

 {  "species" : [  {species content1},  {species content2},  {species content3}...  ]  }  

Вам нужно переместиться на одну глубину глубже, хотя бы еще на один шаг вперед.

 File file = new File("src/main/resources/species.json");  ObjectMapper mapper = new ObjectMapper();  try {  // Json -gt; JsonNode  JsonNode speciesJsonNode = mapper.readTree(file);  // node move one depth deeper. Because jsonNode variable has species  for (JsonNode jsonNode : speciesJsonNode) {  // node move one depth deeper. Because species variable has Species arrays  for (JsonNode species : jsonNode) {  // Get Sourcebook  String sourcebook = species.get("sourcebook").toString();  System.out.println(sourcebook);    // Get Species Name  String name = species.get("name").toString();  System.out.println(name);    System.out.println("==============================");  }  } } catch (JsonProcessingException e) {  e.printStackTrace(); } catch (IOException e) {  e.printStackTrace(); }  

Кроме того, вы не используете класс видов. Я думаю, вы хотите использовать класс видов. Преобразуйте JsonNode в класс видов, хотя и под строкой.

 Species species =mapper.convertValue(speciesNode, Species.class);  

Полный код. Если вы хотите преобразовать JsonNode в класс видов.

 package Specise;  import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List;  import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper;  public class Main2 {  public static void main(String[] args) {   File file = new File("src/main/resources/species.json");   ObjectMapper mapper = new ObjectMapper();  Listlt;Speciesgt; speciess = new ArrayListlt;Speciesgt;();   try {  // Json -gt; JsonNode  JsonNode speciesJsonNode = mapper.readTree(file);  // node move one depth deeper. Because jsonNode variable has species  for (JsonNode jsonNode : speciesJsonNode) {  // node move one depth deeper. Because species variable has Species arrays  for (JsonNode speciesNode : jsonNode) {  // convert Species array to speciess pojo  Species species =mapper.convertValue(speciesNode, Species.class);  speciess.add(species);  }  }  // speciess List print out  speciess.forEach(System.out::println);  } catch (JsonProcessingException e) {  e.printStackTrace();  } catch (IOException e) {  e.printStackTrace();  }  } }  

Комментарии:

1. Спасибо. Вы действительно все объяснили тому, кто пытается выучить язык.