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

时间:2018-08-01 21:01:47

标签: java arrays

我的程序是从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);
    }

3 个答案:

答案 0 :(得分:0)

如果您使用的是 let dbCountToInt32 i64 = try // this throws a conversion exception `Can't cast Int64 to Int32` // int32(int64(i64)) // this throws invalid cast exception `Can't cast Int64 to Int32` // int32(i64) //Works but throws a compiler warning `The type 'int64' does not have any proper subtypes and need not be used as the target of a static coercion` int32(i64 :> int64) with | _ -> 0

,请在if内检查尺寸
org.json.simple.JSONArray

或者如果您使用if(array.size() != 0)

org.json.JSONArray

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您无需使用if条件,因为java的for-each足够聪明来处理此问题。

如果数组没有任何值或为空,那么它将根本不会执行。

因此使用此代码:

for (final JsonElement json : array) { // it will not get executed at all if array is empty
            JSONObject jsonObject = new JSONObject(String.valueOf(json));
                                System.out.println("Inside fromJasonToJava, jsonObject:" + jsonObject);

代替

    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);

        }