Search code examples
javaandroidjsonserializable

To define an object in a constructor in Serializable class


I have a JSON response like below image, and I have made a serializable class named as Project

JSON Response

In the image, I have two objects (emergency_contact, and secondary_owner) inside my an array of one object. I'm trying to figure out whether what to do in order to define the object, since I want that details to be present inside my constructor.

I have done this so far:

public class Project implements Serializable {
   public int id;
   public String name;
   public String additional_information;
   //Now what to do Emergency contact

   public Project(int id, String name, String additional_information){

   }
}

I have thought of doing this, public EmergencyContact emergency = new EmergencyContact(param1, param2).

And make a new class named as EmergencyContact, and do a getter and setter for the params. But after doing this, I'm still confused, how would I define it my constructor?

I know I'm close, but I need some help on that.


Solution

  • Sure. You need to have a:

    public class EmergencyContact implements Serializable {
    
       public String name;
       public String number;
    
       public EmergencyContact(String name, String number){
         // assign fields 
       }
    }
    

    and one for the owner:

    public class EmergencyOwner implements Serializable {
    
       public String name;
       public String number;
    
       public EmergencyOwner(String name, String number){
         // assign the fields
       }
    }
    

    then in your Project class you can add fields of these classes:

    public class Project implements Serializable {
       public int id;
       public String name;
       public String additional_information;
       public EmergencyContact emergency_contact;
       public EmergencyOwner emergency_owner;
    
       public Project(int id, String name, String additional_information, EmergencyContact emergency_contact, EmergencyOwner emergency_owner){
         // assign the fields here as well
       }
    }
    

    that's it. If that's an answer to the question consider to delete this question as it is a duplicated on a 100% :)