-2

Below Json format is my input, i need to count the total based on Object

Students:[
        {
        "Student_id": "101"
        "Name": "Jon",
        "Course" : "Engineer"
        },
        {
        "Student_id": "102"
        "Name": "Snow",
        "Course" : "Medical"
        },
        {
        "Student_id": "103"
        "Name": "Walter",
        "Course" : "Chemistry"
        },
        {
        "Student_id": "104"
        "Name": "White",
        "Course" : "Chemistry"
        }
    ]

When i loop the JsonArray Am not able to count the total?? it will show always count 1,i want output like below format

No Of Students: 4
Total Chemistry Students :2

Below code i tried,

            JsonArray Students=Details.getAsJsonArray("Students");

            for(int i=0;i<Students.size();i++)
            {
                JsonObject Std=Students.get(i).getAsJsonObject();
                String SrdID=Std.get("Student_id").getAsString();

                System.out.println("Student Details----"+SrdID);
            }


            String [] Studentarr=new String[] {"Student_id"};
            int Count=Studentarr.length;

            System.out.println("Count ---"+ Count);

Any Help will be Appreciate!! Thanks In Advance

tisispa1
  • 203
  • 2
  • 3
  • 16

2 Answers2

0

Given that you know the structure for each element in the array is the same, could you create a Student class and have an array of Student objects?

In my experience, it's always better to manipulate objects than pure json, but you've not said in your question if that is a requirement or not, so I'll assume it is.

Therefore, you may find the answer on this similar question useful: how to count length of the JSON array element

Hope this helps!

Joni Sykes
  • 19
  • 2
0

With this structure:

var object = {"Students":[
    {
    "Student_id": "101",
    "Name": "Jon",
    "Course" : "Engineer"
    },
    {
    "Student_id": "102",
    "Name": "Snow",
    "Course" : "Medical"
    },
    {
    "Student_id": "103",
    "Name": "Walter",
    "Course" : "Chemistry"
    },
    {
    "Student_id": "104",
    "Name": "White",
    "Course" : "Chemistry"
    }]};

Now, we can try with JS this:

print(object.Students.length) // print total
print(object.Students.filter(st => st.Course === 'Chemistry').length) // print occurrences

Output is:

> 4
> 2
C.P.O
  • 1,213
  • 2
  • 11
  • 29
  • in java we cant pass the pass st => st.Course === 'Chemistry').length in stream like this coz its not accepted 'Chemistry' it will accept single Char 'e' – tisispa1 Mar 14 '19 at 17:33