Java with JSON file

Joined
Nov 5, 2023
Messages
5
Reaction score
1
I have a class Animal, that extends in Dog and Bagamol and I want to read from a .json file objects of both types and to push into a List. Consider that classes Dog and Bagamol have private members that are the same specified in the json file.

json File
[
{
"type": "Dog", "name": "Bobic",
"age": 3, "price": 1000,
"vaccintated": "yes", "breed": "Doberman",
"height": 100, "weight": 6
},
{
"type": "Bagamol", "name":"Master",
"age": 4, "price": 100000,
"vaccined": "no", "color": "green",
"lenght": 50
}
]

Also, from the list I have to select only objects of one type, for example "Bagamol" and to print them using .stream()
 
Joined
Nov 6, 2023
Messages
11
Reaction score
0
public class MainApp
{
public static List<Animal> read()
{
try
{
File fisier=new File("src/main/resources/package.json");
ObjectMapper map = new ObjectMapper();
List<Animal> list =map.readValue(fisier, new TypeReference<List<Animal>>() {});
return list;
}
catch(IOException ex){
ex.printStackTrace();
}
return null;
}

public static void main(String[] args)
{
List<Animal> planet=read();
for(Animal a: planet){
System.out.println(a);
}

}
}
 
Last edited:
Joined
Nov 6, 2023
Messages
11
Reaction score
0
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME,property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Dog.class,name = "Dog"),
@JsonSubTypes.Type(value=Bagamol.class,name="Bagamol")
})
principal class
 
Joined
Nov 6, 2023
Messages
11
Reaction score
0
If you want to display just dogs use that:

planet.stream().filter(animal -> animal instanceof Dog)
.collect(Collectors.toList()).forEach(dog -> System.out.println(dog));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top