猿问

检查 json 数组是否有任何项目

我的程序是从 AsyncTask 派生的“结果”字符串中获取 Java 对象列表。为此,我需要使用 JsonParser 来获取 JsonArray。如果“结果”字符串是 [],则 JsonArray 也是 []。如何检测此 Json 数组中是否有任何项目。我已经尝试了所有的建议,甚至在“结果”字符串中检测到,对我来说没有任何效果,你能帮忙吗?我的 JsonArray:[]


    try{

        JsonParser parser = new JsonParser();

        JsonArray array = parser.parse(orderList).getAsJsonArray();

        System.out.println("Inside fromJasonToJava, array: " + array); //This prints out array: []

        lst =  new ArrayList<Order>();

        if(array.get(0)!= null) { //It goes wrong here, I need a working "if" condition

            //Value is not null

            for (final JsonElement json : array) {

                JSONObject jsonObject = new JSONObject(String.valueOf(json));

                                    System.out.println("Inside fromJasonToJava, jsonObject:" + jsonObject);


            }

        }

    }catch(Exception e){

        throw new Exception("Convert json to java error [fromJasonToJava()]", e);

    }


跃然一笑
浏览 152回答 3
3回答

喵喔喔

如果您正在使用,则在 if 检查大小的内部&nbsp;org.json.simple.JSONArrayif(array.size()&nbsp;!=&nbsp;0)或者如果你使用&nbsp;org.json.JSONArrayif(array.length()&nbsp;!=&nbsp;0)

幕布斯6054654

您可以使用 if(array.length() > 0)

慕尼黑5688855

您不需要使用 if 条件,因为 java 的 for-each 足够聪明来处理这个问题。如果数组没有任何值或者它是空的,那么它根本不会被执行。所以使用这个代码:for (final JsonElement json : array) { // it will not get executed at all if array is empty&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JSONObject jsonObject = new JSONObject(String.valueOf(json));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Inside fromJasonToJava, jsonObject:" + jsonObject);代替&nbsp; &nbsp; if(array.get(0)!= null) { //It goes wrong here, I need a working "if" condition&nbsp; &nbsp; &nbsp; &nbsp; //Value is not null&nbsp; &nbsp; &nbsp; &nbsp; for (final JsonElement json : array) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JSONObject jsonObject = new JSONObject(String.valueOf(json));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Inside fromJasonToJava, jsonObject:" + jsonObject);&nbsp; &nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答