HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Is there another way / proper way of parsing this JSON array ?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisarraywayjsonparsinganotherproperthere

Problem

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 clusterIdList = new ArrayList();
    List serviceIdList = new ArrayList();
    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.

Solution

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.

Context

StackExchange Code Review Q#2609, answer score: 3

Revisions (0)

No revisions yet.