检查json是否包含字符串值

时间:2017-11-26 15:55:02

标签: java android json

我正在努力使它能够检查字符串是否在json中。我这样做的方法是将json的值放入一个数组中,然后查看它是否包含该值。问题是它一个接一个地检查它。这导致它说用户不在工作班次。然后在下一个循环中,它表示它们正在工作。

 private void CheckIfAlreadyWorking(String result) throws JSONException {
    //removed code to condense
    //result is a json of the days that the user is already working
    if (datematcher.find()) {
        String date = datematcher.group(1); //Date of the shift the user is already working
        JSONArray jsonArray = new JSONArray(result);
        String[] yourshifts = new String[jsonArray.length()];
        boolean end = false;
        for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                yourshifts[i] = obj.getString("date");
            if (yourshifts[i].contains(date)) {
                //Already working that day
                Toast.makeText(getApplicationContext(), "Error: You are already working this day", Toast.LENGTH_SHORT).show();
            } else if(end == false){
                AddShift();
                end = true;
            }
        }

    }
    else {
        //Error
    }
}

2 个答案:

答案 0 :(得分:0)

您可以在您正在制作的Toast之后立即在代码中使用 break; 语句。

因此,如果他们正在处理那个问题,在做完toast之后,break语句将为你结束循环并且不会遍历jsonArray中的其余对象

像这样:

if (yourshifts[i].contains(date)) {
    //Already working that day
    Toast.makeText(getApplicationContext(), "Error: You are already working this day", Toast.LENGTH_SHORT).show();
    break;
}

答案 1 :(得分:0)

试试这样: 拿一个boolean isfound = false;

for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                yourshifts[i] = obj.getString("date");
            if (yourshifts[i].contains(date)) {
                isfound = true;
                break;

            }
        }

现在在循环之外:

if(isFound ==true)
{
    Toast.makeText(getApplicationContext(), "Error: You are already working this day", Toast.LENGTH_SHORT).show();
}
else
{
   AddShift();
}