Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a JSON object which holds some json_array like this: (with org.codehaus.jettison.json.*)

json array:[{"C1":["S1","S2"]},{"C2":["S1","S2"]},{"C3":["S1","S2"]},{"C4":["S1","S2"]}]

I have to get two list,one for keys,another for the elements of each key.I have done like this:

//sample: clusterIdList:[C1, C2, C3, C4] and serviceIdList:[S1, S2, S1, S2, S1, S2, S1, S2]

    //get jsonarray by key = serviceCode
    JSONArray array = incident.getJSONArray("serviceCode");


    List<String> clusterIdList = new ArrayList<String>();
    List<String> serviceIdList = new ArrayList<String>();
    String key="";

    for (int i = 0,length=array.length(); i < length; i++) {
        JSONObject b = array.getJSONObject(i);
        key = b.names().getString(0);
        clusterIdList.add(key);
        JSONArray sublist = b.getJSONArray(key);
        for (int j = 0,sublistLength = sublist.length(); j < sublistLength; j++) {
            serviceIdList.add(sublist.getString(j));
        }
    }

Is this a proper way to do this? or can it be improved? I am trying to improve my code quality and readability.

share|improve this question
    
Looks fine to me. The only thing I'd suggest is to move the declaration of the variable key into the loop: String key = b.names().getString(0); –  RoToRa May 26 '11 at 10:19

1 Answer 1

This can be argued, but I think you can write directly i < array.length(); without noticeable slowdown (if length() does the right thing and is just a getter of a field). Makes the loop slightly more readable, IMHO. Or at least add spaces: int i = 0, length = array.length();

I had a glance at the Jettison site, and couldn't find a JavaDoc page. But if JSONArray implements the Iterable interface, you can use the foreach syntax, even more readable.

I agree with the comment of RoToRa, too.

Otherwise, code looks OK.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.