Utsav Gupta
Utsav Gupta

Reputation: 3971

Json Object with 2 nested objects of same type

I have a very simple question which doesnt seem to have an answer.

I have an object which has 2 objects with same type inside it and they are not arrays. How do i represent it in json?

GroupOfEmployees{

Employee emp1;
Employee emp2;
}

Employee{
String name;
int id;
}

emp1 details: name:first id: 1

emp2 details: name: second id:2

Upvotes: 1

Views: 321

Answers (2)

Prasad Khode
Prasad Khode

Reputation: 6739

if you are looking for the json object which represents GroupOfEmployees object then the sample json will be something like below

{
    "emp1": {
        "name": "name1",
        "id": 1
    },
    "emp2": {
        "name": "name2",
        "id": 2
    }
}

update
when you convert above json into object, you will get an object which holds two employee objects with name emp1 & emp2. Consider the following example

The following is your Employee Class:

public class Employee {
    private String name;

    private int id;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    // getter & setter methods

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Employee [name=");
        builder.append(name);
        builder.append(", id=");
        builder.append(id);
        builder.append("]");
        return builder.toString();
    }
}

The following is GroupOfEmployees class:

public class GroupOfEmployees {
    private Employee emp1;
    private Employee emp2;

    // getters & setters method

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("GroupOfEmployees [emp1=");
        builder.append(emp1);
        builder.append(", emp2=");
        builder.append(emp2);
        builder.append("]");
        return builder.toString();
    }
}

here goes main method:

public static void main(String[] args) {
    Employee emp1 = new Employee("name1", 1);
    Employee emp2 = new Employee("name2", 2);

    GroupOfEmployees groupOfEmployees = new GroupOfEmployees();
    groupOfEmployees.setEmp1(emp1);
    groupOfEmployees.setEmp2(emp2);

    Gson gson = new GsonBuilder().create();

    String jsonValue = gson.toJson(groupOfEmployees);
    System.out.println("jsonValue = " + jsonValue);

    GroupOfEmployees newGroup = gson.fromJson(jsonValue, GroupOfEmployees.class);
    System.out.println("Object value = " + newGroup);
}

and finally output is :

jsonValue = {"emp1":{"name":"name1","id":1},"emp2":{"name":"name2","id":2}}
Object value = GroupOfEmployees [emp1=Employee [name=name1, id=1], emp2=Employee [name=name2, id=2]]

Upvotes: 1

minas
minas

Reputation: 230

Make a JSONArray:

[
{
name: "name1",
id: = id1 }, 
{
name: "name2",
id: = id2 }
]

Upvotes: 1

Related Questions