简体   繁体   English

如何计算 JsonArray 内的对象?

[英]How to count the object inside the JsonArray?

Below Json format is my input, i need to count the total based on Object以下 Json 格式是我的输入,我需要根据 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??当我循环 JsonArray 时无法计算总数?? it will show always count 1,i want output like below format它将始终显示计数 1,我希望输出如下格式

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提前致谢

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?鉴于您知道数组中每个元素的结构都是相同的,您能否创建一个 Student 类并拥有一个 Student 对象数组?

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.根据我的经验,操作对象总是比纯 json 更好,但是你没有在你的问题中说这是否是一个要求,所以我假设它是。

Therefore, you may find the answer on this similar question useful: how to count length of the JSON array element因此,您可能会发现这个类似问题的答案很有用: 如何计算 JSON 数组元素的长度

Hope this helps!希望这可以帮助!

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:现在,我们可以用 JS 试试这个:

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

Output is:输出是:

> 4
> 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM