How to created a nested json in java

Viewed 50

How to created a nested json in java.

I have a dto like this and in my service implemntation I am returing element based on this dto.

public class CountDTO {

    private int role;
    private String subject;
    private int count;
}

my service impl :

List<CountDTO> countTemp = new ArrayList<>();

for loop { // some loop for individual query :
    CountDTO myList =  new CountDTO(role,subject,count);
    countTemp.add(myList);
}
return countTemp; 

This is my element which I am getting from above code. countTemp is my input which give me this result

[   {
            role : 10,
            subject : math,
            count : 5
    },{
            role : 20,
            subject : math,
            count : 5
    },{
            role : 10,
            subject : Science,
            count : 2
    },{
            role : 20,
            subject : Science,
            count : 5
    },{
            role : 10,
            subject : English,
            count : 5
    },
]

Now the problem is I need my data like this. count based on the role and subject, this will be my output : ' I want to convert like this.

    [
    {
        role : [
            {
                role : 10,
                count : 12
            },{
                role : 20,
                count : 10
            }
        ],
        subject : [
            {
                subject : math,
                count : 10
            },{
                subject : science,
                count : 7
            },{
                subject : history,
                count : 5
            }
        ]    
    }
    
]

My question which data structure i should choose and what should be return type, since dto is not valid in this scenario. Can anybody help me how to do that.

0 Answers
Related