AKIWEB
AKIWEB

Reputation: 19612

Parse the JSON String efficiently and in a clean way

In my below code, colData stores JSON String. Sample example for colData-

{"lv":[{"v":{"price":70.0,"userId":419},"cn":3},
       {"v":{"price":149.99,"userId":419},"cn":3},
       {"v":{"price":54.95,"userId":419},"cn":3}],
 "lmd":20130206212543}

Now I am trying to match id value with userId value in the above JSON String. I am getting id value from a different source. Meaning if id value is 419 then in the above JSON String userId value should also be 419. And in the JSON String, it might be possible there are lot of userId values so all the userId values should be matching with id. If any of them doesn't matches then log the exception.

So I was trying something like this-

final int id = generateRandomId(random);

for (String str : colData) {
    if (!isJSONValid(str, id)) {
        // log the exception here
        LOG.error("Invalid JSON String " +str+ "with id" +id);
    }
}

public boolean isJSONValid(final String str, final int id) {
    boolean valid = false;
    try {
        final JSONObject obj = new JSONObject(str);
        final JSONArray geodata = obj.getJSONArray("lv");
        final int n = geodata.length();

        for (int i = 0; i < n; ++i) {
            final JSONObject person = geodata.getJSONObject(i);
            JSONObject  menu = person.getJSONObject("v");
            if(menu.getInt("userId") == id) {
                valid = true;
            }
        }
    } catch (JSONException ex) {
        valid = false;
    }
    return valid;
}

As per my understanding it looks like I can make isJSONValid method more cleaner. In my above isJSONValid method as I am repeating some stuff which I shouldn't be doing. Can anyone help me out how to make this more cleaner if I have missed anything. I will be able to learn some more stuff. Thanks for the help

Upvotes: 1

Views: 943

Answers (1)

yair
yair

Reputation: 9245

You can initialize valid = true and set it to false when you find a non-valid userId and immediately fail:

public boolean isJSONValid(final String str, final int id) {
    boolean valid = true;
    try {
        final JSONObject obj = new JSONObject(str);
        final JSONArray geodata = obj.getJSONArray("lv");
        final int n = geodata.length();

        for (int i = 0; i < n; ++i) {
            final JSONObject person = geodata.getJSONObject(i);
            JSONObject  menu = person.getJSONObject("v");
            if(menu.getInt("userId") != id) {
                valid = false;
                break;
            }
        }
    } catch (JSONException ex) {
        valid = false;
    }
    return valid;
}

This way you iterate through all array's elements only if all are valid, which is the only case you actually have to.

Upvotes: 3

Related Questions