Unable to initialize an object through constructors in Java: Erroneous Compilation - java

This code below keeps throwing the following error:
Java Error Terminal Screen Snapshot
I've tried quite a few online fixes but they don't seem to be working.
My code is below and I've commented the error location(occurs in the driver main function)
NOTE: The code compiles properly if I change public static void main(String args[]) to public void main(String args[]) but when i run it, it throws the error "Change main to static void main". I'm a little stuck here.
import java.util.*;
class Exercise{ //Exercise Begins
class UtilityFunctions{
public String getAuthor(){ return "";};
public String getPublisher(){return "";};
public void display(){};
}
class Book extends UtilityFunctions{
private String title;
private String author;
private String category;
private String datePublished;
private String publisher;
private double price;
public Book(String authorParam, String publisherParam){
author = authorParam;
publisher = publisherParam;
}
//List of Setters
public void setTitle(String title){
this.title = title;
}
public void setCategory(String cat){
this.category = cat;
}
public void setDatePublished(String dp){
this.datePublished = dp;
}
public void setPrice(double p){
this.price = p;
}
//List of Getters
public String getTitle(){
return this.title;
}
#Override
public String getAuthor(){
return this.author;
}
public String getCategory(){
return this.category;
}
public String getDatePublished(){
return this.datePublished;
}
#Override
public String getPublisher(){
return this.publisher;
}
public double getPrice(){
return this.price;
}
#Override
public void display(){
System.out.println("Book Title:" + getTitle());
System.out.println("Author:" + getAuthor());
System.out.println("Category:" + getCategory());
System.out.println("Date Published:" + getDatePublished());
System.out.println("Publisher:" + getPublisher());
System.out.println("Price:$" + getPrice());
}
}
class Author extends UtilityFunctions{
private String authorName;
private String birthDate;
private String publisher;
private String email;
private String gender;
List<Book> bookList;
public Author(String publisherParam){
publisher = publisherParam;
}
public void addBook(Book b){
bookList.add(b);
}
//List of Setters
public void setName(String n){
this.authorName = n;
}
public void setEmail(String em){
this.email = em;
}
public void setGender(String gen){
this.gender = gen;
}
public void setBirthDate(String dob){
this.birthDate = dob;
}
//List of Getters
public String getAuthor(){
return this.authorName;
}
public String getPublisher(){
return this.publisher;
}
public String getEmail(){
return this.email;
}
public String getGender(){
return this.gender;
}
public String getBirthDate(){
return this.birthDate;
}
#Override
public void display(){
System.out.println("Author Name:" + getAuthor());
System.out.println("Email:" + getEmail());
System.out.println("Gender:" + getGender());
System.out.println("BirthDate:" + getBirthDate());
System.out.println("Publisher:" + getPublisher());
System.out.println("BOOKS:");
for(Book b:bookList){
b.display();
System.out.println();
}
}
}
class Publisher extends UtilityFunctions{
private String publisherName;
private String publisherAddress;
private String publisherEmail;
private int publisherPhoneNumber;
List<Author> authorList;
public Publisher(String name, String add, String email,int phone){
publisherName = name;
publisherAddress = add;
publisherEmail = email;
publisherPhoneNumber = phone;
}
public void addAuthor(Author a){
authorList.add(a);
}
//List of Getters
public String getPublisher(){
return this.publisherName;
}
public String getAddress(){
return this.publisherAddress;
}
public String getEmail(){
return this.publisherEmail;
}
public int getPhoneNumber(){
return this.publisherPhoneNumber;
}
#Override
public void display(){
System.out.println("Publisher Name:" + getPublisher());
System.out.println("Publisher Address:" + getAddress());
System.out.println("Publisher Phone Number:" + getPhoneNumber());
System.out.println("Publisher Email:" + getEmail());
System.out.println("AUTHORS:");
for(Author a:authorList){
a.display();
System.out.println("-------------------------------------");
}
System.out.println("--------------------------------------------------------------------------------");
System.out.println("--------------------------------------------------------------------------------");
}
}
public static void main(String args[]){
ArrayList<Publisher> publisherList = new ArrayList<Publisher>();
//1st ERROR HERE
Publisher pub1 = new Publisher("Riverhead Books","8080 Cross Street","riverhead#riverheadbooks.co.uk",784646533);
//2nd ERROR HERE
Author author1 = new Author(pub1.getPublisher());
author1.setName("Khaled Hosseini");
author1.setGender("Male");
author1.setBirthDate("1965-10-09");
author1.setEmail("khaledhosseini#gmail.com");
pub1.addAuthor(author1);
//3rd ERROR HERE
Book book1 = new Book(author1.getAuthor(),author1.getPublisher());
book1.setTitle("Kite Runner");
book1.setCategory("Historical-Fiction|Drama");
book1.setPrice(39.95);
book1.setDatePublished("2003-05-29");
author1.addBook(book1);
publisherList.add(pub1);
for(Publisher p:publisherList){
p.display();
}
}
}//Exercise Ends

All your classes : Book, Author, Publisher, UtilityFunctions ... should be outside the Exercise class
Class Exercise {
public static void main(String args[]) {...}
} // end class exercice
Class UtilityFunctions {...}
Class Book {...}
Class Author {...}
Class Publisher {...}

Related

How do I leverage a json mapping file to convert from one pojo to another pojo?

I have two POJOs (Person.java and User.java) that contain similar information. See below:
public class Person {
private String first_name;
private String last_name;
private Integer age;
private Integer weight;
private Integer height;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
public class User {
private String name_first;
private String name_last;
private Integer my_age;
private Integer my_weight;
private String social_security;
public String getName_first() {
return name_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public String getName_last() {
return name_last;
}
public void setName_last(String name_last) {
this.name_last = name_last;
}
public Integer getMy_age() {
return my_age;
}
public void setMy_age(Integer my_age) {
this.my_age = my_age;
}
public Integer getMy_weight() {
return my_weight;
}
public void setMy_weight(Integer my_weight) {
this.my_weight = my_weight;
}
public String getSocial_security() {
return social_security;
}
public void setSocial_security(String social_security) {
this.social_security = social_security;
}
}
I have defined a mapping.json file as shown below using GSON.
{
"columnMap": [
{
"userColumn": "name_first",
"personColumn": "first_name"
},
{
"userColumn": "last_first",
"personColumn": "first_last"
},
{
"userColumn": "my_age",
"personColumn": "age"
},
{
"userColumn": "my_weight",
"personColumn": "weight"
}
]
}
public class Mapping {
private ArrayList<Pair> columnMap;
public Mapping(){
columnMap = new ArrayList<>();
}
public ArrayList<Pair> getColumnMap() {
return columnMap;
}
public void setColumnMap(ArrayList<Pair> columnMap) {
this.columnMap = columnMap;
}
}
I am writing a utility class helper function that converts between a Person and User object the mapped pairs.
public class Pair {
private String userColumn;
private String personColumn;
public String getUserColumn() {
return userColumn;
}
public void setUserColumn(String userColumn) {
this.userColumn = userColumn;
}
public String getPersonColumn() {
return personColumn;
}
public void setPersonColumn(String personColumn) {
this.personColumn = personColumn;
}
public static void main(String args[]){
}
}
My question is below:
As you can see the returnVal object is being set by me (the programmer) to convert from a User POJO to a Person POJO. How do I leverage the pre-defined mapping.json to do this? The reason I am asking is in the future, the mapping.json file may change (maybe the weight mapping no longer exists). So I am trying to avoid re-programming this Utility.userToPerson() function. How can I achieve this? I am thinking Java reflection is the way to go, but I would like to hear back from the Java community.
public class Utility {
public static Person userToPerson(User u){
Person returnVal = new Person();
returnVal.setAge(u.getMy_age()); // <-- Question How do I leverage mapping.json here?
returnVal.setFirst_name(u.getName_first());
returnVal.setLast_name(u.getName_last());
returnVal.setWeight(u.getMy_weight());
return returnVal;
}
}
You can introspect the beans (i.e. User and Person) for the field names and call corresponding getter from User to fetch the value. Later call corresponding setter in Person.
Here I have taken userToPersonFieldsMap for mapping the field, you can load mapping from JSON file and construct the map accordingly.
Important code section is the for loop, where it dynamically calls getter and setter and does the job.
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class UserToPersonMapper {
public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Map<String, String> userToPersonFieldsMap = new HashMap<>();
userToPersonFieldsMap.put("name_first", "first_name");
userToPersonFieldsMap.put("last_first", "first_last");
userToPersonFieldsMap.put("age", "personAge");
//existing user
User user = new User("Tony", "Stark", 20);
//new person - to be initialised with values from user
Person person = new Person();
for (Map.Entry<String, String> entry : userToPersonFieldsMap.entrySet()) {
Object userVal = new PropertyDescriptor(entry.getKey(), User.class).getReadMethod().invoke(user);
new PropertyDescriptor(entry.getValue(), Person.class).getWriteMethod().invoke(person, userVal);
}
System.out.println(user);
System.out.println(person);
}
}
class User {
private String name_first;
private String last_first;
private int age;
public User(String name_first, String last_first, int age) {
this.name_first = name_first;
this.last_first = last_first;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName_first() {
return name_first;
}
public String getLast_first() {
return last_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public void setLast_first(String last_first) {
this.last_first = last_first;
}
#Override
public String toString() {
return "User{" +
"name_first='" + name_first + '\'' +
", last_first='" + last_first + '\'' +
", age=" + age +
'}';
}
}
class Person {
private String first_name;
private String first_last;
private int personAge;
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public void setFirst_last(String first_last) {
this.first_last = first_last;
}
public String getFirst_name() {
return first_name;
}
public String getFirst_last() {
return first_last;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
#Override
public String toString() {
return "Person{" +
"first_name='" + first_name + '\'' +
", first_last='" + first_last + '\'' +
", personAge=" + personAge +
'}';
}
}
You can tweak and try it out this example to make it more align with your requirement.
Note:
This solution uses reflection.

How can I create a instance of a class with an array of Strings as the only instance variable?

I have written a class Form. An array of 10 Strings is the only parameter in the constructor. How can I create an instance of the class? I'm sure there are other problems in my setters and getters but I cant test them until I fix this.
public class FormLab {
public static void main(String[]args){
Form f1 = new Form(String webForm);
System.out.println(print(String[] webForm));
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}
}
public class Form {
String[] webForm = new String[10];
private String userID;
private String pw;
private String pw2;
private String email;
private String name;
private String address;
private String city;
private String state;
private String zip;
private String telephone;
//constructor
public Form(String[] webForm){
//filling array with field values
webForm[0] = "0123456789";
webForm[1] = "java123";
webForm[2] = "java123";
webForm[3] = "luke.skywalker#jedi.com";
webForm[4] = "Luke Skywalker";
webForm[5] = "1234 The Force Way";
webForm[6] = "Rome";
webForm[7] = "GA";
webForm[8] = "30161";
webForm[9] = "7065551234";
}
public boolean getEmptyFields() {
//boolean empty = false;
for(int i = 0; i < webForm.length; i++){
if(webForm[i]!= null){
return true;
}
}
return false;
}
public String getUserID(){
return userID;
}
public void setUserId(String userID){
this.userID = userID;
}
public String getPw(){
return pw;
}
public void setPw(String pw){
this.pw = pw;
}
public String getPw2(){
return pw2;
}
public void setPw2(String pw2){
this.pw2 = pw2;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public String getCity(){
return city;
}
public void setCity(String city){
this.city = city;
}
public String getState(){
return state;
}
public void setState(String state){
this.state = state;
}
public String getZip(){
return userID;
}
public void setZip(String zip){
this.zip = zip;
}
public String getTelephone(){
return telephone;
}
public void setTelephone(String telephone){
this.telephone = telephone;
}
public int getCharNum(String userID) {
int userLength = 0;
//userID.length();
return userLength;
}
public boolean getPwCheck() {
boolean check = pw.equalsIgnoreCase(pw2);
// pw.equalsIgnoreCase(pw2);
return check;
}
public boolean getEmailCheck(String email) {
if(email.contains("#") && email.contains(".")){
return true;
}
return false;
}
public static void getPrint(String[] webForm) {
System.out.println(webForm.toString());
}
}
Use method arraycopy.
public Form(String[] webForm){
System.arraycopy(webForm, 0, this.webForm, 0, webForm.length);
}
The constructor takes a string array as argument, but you are passing it a string, try:
myList = new String[];
myForm = new Form(myList);
You need to declare your array before putting it as a parameter as follow:
public class FormLab {
public static void main(String[]args){
String webForm = new String[10];
Form f1 = new Form(webForm);
/*System.out.println(print(String[] webForm)); THIS IS WRONG*/
/*TO PRINT THE VALUES IN THE ARRAY YOU NEED TO WRITE A METHOD IN UR
FORM CLASS THAT WILL LOOP THRU UR VARIABLE AND PRINT*/
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}

Adding Items to my inventory in Java

I am making a text-based game on JavaFX, and after I hit a tree, I want to get Oak logs.
I have already built my inventory, and I have put default items in it such as Water, Bread, etc.
I am trying to add my Oak Logs to my inventory, but nothing is working.
Here is a part of my code:
Item ItemList[] = {new Bread(), new OakLog()};
Optional<ButtonType> result = alert.showAndWait();
if(result.get() == buttonTypeOak) {
woodcuttingXP = woodcuttingXP + oakXP;
dialogue.appendText("You swing at an Oak tree. + " + oakXP + "XP.\n");
dialogue.appendText("You gathered 1 log.\n");
mainCharacter.getInventory().add(new OakLog());
}
Here is my Item Class:
package game;
public class Item {
private String name;
private int weight;
private int quantity;
private int value;
private String description;
public Item(String name, int value, String description) {
this.name = name;
this.value = value;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return getName();
}
}
And finally, here is my Character class:
package game;
import java.util.ArrayList;
import beverages.Water;
import items.OakLog;
import rawFood.Bread;
public class Character {
private String name;
private int hydrationLevel;
private int healthLevel;
private int hungerLevel;
private int woodcuttingLevel;
public int getWoodcuttingLevel() {
return woodcuttingLevel;
}
public void setWoodcuttingLevel(int woodcuttingLevel) {
this.woodcuttingLevel = woodcuttingLevel;
}
public int getHungerLevel() {
return hungerLevel;
}
public void setHungerLevel(int hungerLevel) {
this.hungerLevel = hungerLevel;
}
private ArrayList<Item> inventory = new ArrayList<Item>();
public ArrayList<Item> getInventory() {
return inventory;
}
public void setInventory(ArrayList<Item> inventory) {
this.inventory = inventory;
}
//creates a person with two basic items
public Character(String name){
this.name = name;
this.hydrationLevel = 100;
this.healthLevel = 100;
this.hungerLevel = 100;
this.woodcuttingLevel = 1;
addToInventory (new Bread());
addToInventory (new OakLog());
addToInventory (new Water());
}
//GETTERS AND SETTERS
public String getName() {
return name;
}
public int getHydrationLevel() {
return hydrationLevel;
}
public void setHydrationLevel(int hydrationLevel) {
this.hydrationLevel = hydrationLevel;
}
public int getHealthLevel() {
return healthLevel;
}
public void setHealthLevel(int healthLevel) {
this.healthLevel = healthLevel;
}
//END GETTERS AND SETTERS
/*Method Name: eat()
*Method Inputs: a piece of food
*Method Purpose: Will allow the user to eat food
*/
public Item getItemFromInventory(int index){
Item item = inventory.get(index);
return item;
}
public void addToInventory(Item item){
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
else{
item.setQuantity(1);
inventory.add(item);
}
}
public String toString(){
return "Character Stats:\nName:" + getName() + "\nHydration: " + getHydrationLevel() + "\nHealth: " + getHealthLevel() + "\nWoodcutting: " + getWoodcuttingLevel();
}
}
In your code, you have:
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
This just updates the quantity of the local variable item in the method, not the item in the inventory.

Why is my code not displaying these 2 Arraylists?

I need to display an ArrayList with a list of college degree/s that an individual may have.
In another ArrayList, I need display the list of individual/s that meet the requirement of college degree that a company is asking.
Tried a system.out inside the loops and it's not even accessing the for loops.
*The 2 methods with the for loops are at the end of this class
import java.util.ArrayList;
public class RecruitingCompany {
private String companyName;
private int phoneNumber;
private String address;
private ArrayList<CollegeDegree> collegeDegreeList = new ArrayList<>();
private ArrayList<Candidate> candidateList = new ArrayList<>();
private Candidate candidate;
private Requirement academicDegree;
public RecruitingCompany(){
/*main constructor*/
}
public RecruitingCompany(String companyName, int phoneNumber, String address){
this.companyName = companyName;
this.phoneNumber = phoneNumber;
this.address = address;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public ArrayList<CollegeDegree> getCollegeDegreeList() {
return collegeDegreeList;
}
public void setCollegeDegreeList(ArrayList<CollegeDegree> collegeDegreeList) {
this.collegeDegreeList = collegeDegreeList;
}
public ArrayList<Candidate> getCandidateList() {
return candidateList;
}
public void setCandidateList(ArrayList<Candidate> candidateList) {
this.candidateList = candidateList;
}
public Candidate getCandidate() {
return candidate;
}
public void setCandidate(Candidate candidate) {
this.candidate = candidate;
}
public Requirement getAcademicDegree() {
return academicDegree;
}
public void setAcademicDegree(Requirement academicDegree) {
this.academicDegree = academicDegree;
}
public String showCandidateCollegeDegrees(){
String degree = "Candidato: " + candidate.getName() + "\n";
for (CollegeDegree cd: this.collegeDegreeList){
degree += cd.toString();
}
return degree;
}
public String selectByCollegeDegree(){
String person = "Título: " + academicDegree.getDegree() + "\n";
for (Candidate c: this.candidateList){
person += c.toString();
}
return person;
}
}
The Tester class
public class Tester {
public static void main(String[] args) {
AvailableJob availableJob = new AvailableJob(2005, 2011, "Contador", 444464444, "Metalco", "del poste de luz, 50m oeste", 550.000);
Candidate candidate = new Candidate("Asdrubal", 888888888, "Asdrubal#yahoo.com", "Bachillerato");
CollegeDegree collegeDegree = new CollegeDegree("Bachillerato Administracion", 2003, "Universidad Aguila Calva");
RecruitingCompany recruitingCo = new RecruitingCompany();
Requirement requirement = new Requirement("Bachillerato", 4);
recruitingCo.setCandidate(candidate);
recruitingCo.setAcademicDegree(requirement);
availableJob.setRequirement(requirement);
System.out.println(recruitingCo.showCandidateCollegeDegrees());
System.out.println();
System.out.println(recruitingCo.selectByCollegeDegree());
System.out.println();
System.out.println(availableJob.showRequirement());
//System.out.print(recruitingCo.getCandidateList());
}
}
You are not adding the new candidate or degree to the arraylists. Change the following methods it will work,
public void setAcademicDegree(Requirement academicDegree) {
this.academicDegree = academicDegree;
collegeDegreeList.add(academicDegree);
}
and
public void setCandidate(Candidate candidate) {
this.candidate = candidate;
candidateList.add(candidate);
}
Now when you set a new Candidate object or CollegeDegree object it will be automatically added to the lists.
In your code, you need to do some changes:
setCollegeDegreeList(), setCandidateList() and setCandidate() methods
should be changed to addCollegDegree() and addCandidate()
recruitingCo.setCandidate(candidate) should be replaced to
recruitingCo.addCandidate(candidate);
Need to add recruitingCo.addCollegeDegree(collegeDegree); in main();
And you can get following code:
import java.util.ArrayList;
public class RecruitingCompany {
private String companyName;
private int phoneNumber;
private String address;
private ArrayList<CollegeDegree> collegeDegreeList = new ArrayList<>();
private ArrayList<Candidate> candidateList = new ArrayList<>();
private Requirement academicDegree;
public RecruitingCompany(){
/*main constructor*/
}
public RecruitingCompany(String companyName, int phoneNumber, String address){
this.companyName = companyName;
this.phoneNumber = phoneNumber;
this.address = address;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public ArrayList<CollegeDegree> getCollegeDegreeList() {
return collegeDegreeList;
}
public ArrayList<Candidate> getCandidateList() {
return candidateList;
}
public void addCollegeDegree(CollegeDegree collegeDegree) {
this.collegeDegreeList.add(collegeDegree);
}
public void addCandidate(Candidate candidate) {
this.candidateList.add(candidate);
}
public Requirement getAcademicDegree() {
return academicDegree;
}
public void setAcademicDegree(Requirement academicDegree) {
this.academicDegree = academicDegree;
}
public String showCandidateCollegeDegrees(){
String degree = "Candidato: " + candidate.getName() + "\n";
for (CollegeDegree cd: this.collegeDegreeList){
degree += cd.toString();
}
return degree;
}
public String selectByCollegeDegree(){
String person = "Título: " + academicDegree.getDegree() + "\n";
for (Candidate c: this.candidateList){
person += c.toString();
}
return person;
}
}
Tester:
public class Tester {
public static void main(String[] args) {
AvailableJob availableJob = new AvailableJob(2005, 2011, "Contador", 444464444, "Metalco", "del poste de luz, 50m oeste", 550.000);
Candidate candidate = new Candidate("Asdrubal", 888888888, "Asdrubal#yahoo.com", "Bachillerato");
CollegeDegree collegeDegree = new CollegeDegree("Bachillerato Administracion", 2003, "Universidad Aguila Calva");
RecruitingCompany recruitingCo = new RecruitingCompany();
Requirement requirement = new Requirement("Bachillerato", 4);
recruitingCo.addCandidate(candidate);
recruitingCo.addСollegeDegree(collegeDegree);
recruitingCo.setAcademicDegree(requirement);
availableJob.setRequirement(requirement);
System.out.println(recruitingCo.showCandidateCollegeDegrees());
System.out.println();
System.out.println(recruitingCo.selectByCollegeDegree());
System.out.println();
System.out.println(availableJob.showRequirement());
//System.out.print(recruitingCo.getCandidateList());
}
}

How to get values from JSON pojo

I am very new to JSON and jackson, currently I have pojo files and I am trying to get the data and store it in an array. for example I want to extract Network name and store it an array and later display or compare it with live site data.
here is the main pojo file -
public class JsonGen{
private String _type;
private List cast;
private List clips;
private Common_sense_data common_sense_data;
private String common_sense_id;
private List crew;
private String description;
private List episodes;
private Number franchise_id;
private List genres;
private String guid;
private Images images;
private boolean is_locked;
private boolean is_mobile;
private boolean is_parental_locked;
private String kind;
private List mobile_networks;
private String most_recent_full_episode_added_date;
private String name;
private List networks;
private List platforms;
private List ratings;
private String release_date;
private List season_filters;
private String slug;
private String tms_id;
public String get_type(){
return this._type;
}
public void set_type(String _type){
this._type = _type;
}
public List getCast(){
return this.cast;
}
public void setCast(List cast){
this.cast = cast;
}
public List getClips(){
return this.clips;
}
public void setClips(List clips){
this.clips = clips;
}
public Common_sense_data getCommon_sense_data(){
return this.common_sense_data;
}
public void setCommon_sense_data(Common_sense_data common_sense_data){
this.common_sense_data = common_sense_data;
}
public String getCommon_sense_id(){
return this.common_sense_id;
}
public void setCommon_sense_id(String common_sense_id){
this.common_sense_id = common_sense_id;
}
public List getCrew(){
return this.crew;
}
public void setCrew(List crew){
this.crew = crew;
}
public String getDescription(){
return this.description;
}
public void setDescription(String description){
this.description = description;
}
public List getEpisodes(){
return this.episodes;
}
public void setEpisodes(List episodes){
this.episodes = episodes;
}
public Number getFranchise_id(){
return this.franchise_id;
}
public void setFranchise_id(Number franchise_id){
this.franchise_id = franchise_id;
}
public List getGenres(){
return this.genres;
}
public void setGenres(List genres){
this.genres = genres;
}
public String getGuid(){
return this.guid;
}
public void setGuid(String guid){
this.guid = guid;
}
public Images getImages(){
return this.images;
}
public void setImages(Images images){
this.images = images;
}
public boolean getIs_locked(){
return this.is_locked;
}
public void setIs_locked(boolean is_locked){
this.is_locked = is_locked;
}
public boolean getIs_mobile(){
return this.is_mobile;
}
public void setIs_mobile(boolean is_mobile){
this.is_mobile = is_mobile;
}
public boolean getIs_parental_locked(){
return this.is_parental_locked;
}
public void setIs_parental_locked(boolean is_parental_locked){
this.is_parental_locked = is_parental_locked;
}
public String getKind(){
return this.kind;
}
public void setKind(String kind){
this.kind = kind;
}
public List getMobile_networks(){
return this.mobile_networks;
}
public void setMobile_networks(List mobile_networks){
this.mobile_networks = mobile_networks;
}
public String getMost_recent_full_episode_added_date(){
return this.most_recent_full_episode_added_date;
}
public void setMost_recent_full_episode_added_date(String most_recent_full_episode_added_date){
this.most_recent_full_episode_added_date = most_recent_full_episode_added_date;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public List getNetworks(){
return this.networks;
}
public void setNetworks(List networks){
this.networks = networks;
}
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
public List getRatings(){
return this.ratings;
}
public void setRatings(List ratings){
this.ratings = ratings;
}
public String getRelease_date(){
return this.release_date;
}
public void setRelease_date(String release_date){
this.release_date = release_date;
}
public List getSeason_filters(){
return this.season_filters;
}
public void setSeason_filters(List season_filters){
this.season_filters = season_filters;
}
public String getSlug(){
return this.slug;
}
public void setSlug(String slug){
this.slug = slug;
}
public String getTms_id(){
return this.tms_id;
}
public void setTms_id(String tms_id){
this.tms_id = tms_id;
}
}
here is the Network Pojo class -
public class Networks{
private String banner;
private String description;
private boolean is_locked;
private String logo;
private String name;
private String network_analytics;
private Number network_id;
private String slug;
private String thumbnail_url;
private String url;
public String getBanner(){
return this.banner;
}
public void setBanner(String banner){
this.banner = banner;
}
public String getDescription(){
return this.description;
}
public void setDescription(String description){
this.description = description;
}
public boolean getIs_locked(){
return this.is_locked;
}
public void setIs_locked(boolean is_locked){
this.is_locked = is_locked;
}
public String getLogo(){
return this.logo;
}
public void setLogo(String logo){
this.logo = logo;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getNetwork_analytics(){
return this.network_analytics;
}
public void setNetwork_analytics(String network_analytics){
this.network_analytics = network_analytics;
}
public Number getNetwork_id(){
return this.network_id;
}
public void setNetwork_id(Number network_id){
this.network_id = network_id;
}
public String getSlug(){
return this.slug;
}
public void setSlug(String slug){
this.slug = slug;
}
public String getThumbnail_url(){
return this.thumbnail_url;
}
public void setThumbnail_url(String thumbnail_url){
this.thumbnail_url = thumbnail_url;
}
public String getUrl(){
return this.url;
}
public void setUrl(String url){
this.url = url;
}
}
and here is my code through which I am trying to extract the network names -
public class util {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
List<JsonGen> jsongenShow = null;
String url1 = "http://www.dishanywhere.com/radish/v20/dol/home/carousels/shows.json";
getShowNWGopherParser(nwork, url1);
}
public static String[] getShowNWGopherParser (List<Networks> nwork, String url ) throws JsonParseException, JsonMappingException, IOException
{
URL jsonUrl = new URL(url);
ObjectMapper objmapper = new ObjectMapper();
//objmapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
nwork = objmapper.readValue(jsonUrl, new TypeReference<List<Networks>>() {});
String [] shows = new String [nwork.size()];
int i = 0;
for(Networks element : nwork) {
shows[i++]=element.getUrl();
}
for(int j =0; j<shows.length;j++)
{
System.out.println(shows[j]);
}
return shows;
}
}
and here is the error -
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "networks" (class featureshows.Networks), not marked as ignorable (10 known properties: , "logo", "slug", "name", "banner", "network_id", "url", "network_analytics", "description", "thumbnail_url", "is_locked"])
at [Source: http://www.dishanywhere.com/radish/v20/dol/home/carousels/shows.json; line: 1, column: 15] (through reference chain: featureshows.Networks["networks"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:79)
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:568)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:650)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:830)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:310)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:112)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:226)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:203)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:23)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2563)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1789)
at functions.util.getShowNWGopherParser(util.java:77)
at functions.util.main(util.java:31)
The reason is that you're using a regular List interface for your list of networks instead of the generic version with the bounds for the expected type.
Try changing the field declaration from:
private List networks;
to
private List<Networks> networks;
While you're at it, it looks like you're using the regular List interface pretty much everywhere. You'll probably run into more issues if you don't convert them all to include the type you expect in the list.
Essentially, you're not providing enough information about the type of object you expect in the list for jackson to figure out what to populate it with. You can read more about generics here: http://docs.oracle.com/javase/tutorial/extra/generics/intro.html
EDIT:
It looks (from your comment) that you've already tried disabling checks for unknown properties, but try adding this annotation to your Networks class:
#JsonIgnoreProperties(ignoreUnknown = true)

Categories