使用Java找不到JSONArray [5]

时间:2018-04-03 10:19:58

标签: java arrays json exception jersey

我的Json回应是

    "results": [
            [
                "2C30AE32-191@Local",
                "Imperva Inc.",
                "SecureSphere",
                "Custom Violation",
                1,
                "",
                "KMB",
                "196.207.98.94",
                "10.10.1.180",
                "10.10.18.14",
                443,
                "",
                7874115,
                "",
                1522716763000,
                "TCP",
                "",
                "",
                ""
            ]
        ]

我的java代码:

           String output = response.getEntity(String.class);

            JSONObject obj = new JSONObject(output);

            JSONArray results = obj.getJSONArray("results");

                JSONArray first = (JSONArray) results.get(1);

                String deviceVendor = (String) first.get(0);

                String deviceProduct =  (String) first.get(1);

                String name = (String) first.get(2);

                String baseEventCount = (String) first.get(3);

                String categoryOutcome = (String) first.get(4);

                String customerName = (String) first.get(5);

                String sourceAddress = (String) first.get(6);

                String destinationAddress = (String) first.get(7);

                String deviceAddress = (String) first.get(8);

                String destinationPort = (String) first.get(9);

                String destinationServiceName = (String) first.get(10);

                String eventId = (String) first.get(11);

                String message = (String) first.get(12);

                String startTime = (String) first.get(13);

                String transportProtocol = (String) first.get(14);

                String categoryBehavior = (String) first.get(15);

                String categoryDeviceGroup = (String) first.get(16);

                String categoryObject = (String) first.get(17);

在这里,我正在使用索引号来获取数据。当我解析它时,我得到JSONArray [5]未找到异常。怎么处理这个。如果我们有一个json对象,我们可以使用.has("string")处理,但如果它是json数组,如何处理这种情况?

1 个答案:

答案 0 :(得分:0)

I have use simplejson you can replace the net.sf.JSON    

it's working.

            JSONParser parser = new JSONParser();
            Object obj = parser.parse(new FileReader("C:\\Users\\user\\Desktop\\results.json"));
            org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) obj;
            org.json.simple.JSONArray  departures = (org.json.simple.JSONArray)  jsonObject.get("results");    

            for(int i=0;i<departures.size();i++){ 
                System.out.println("all =="+departures.get(0));
                org.json.simple.JSONArray all = (org.json.simple.JSONArray) departures.get(0); 
                System.out.println("test =="+all.get(5));
            }