5
\$\begingroup\$

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.

asked May 25, 2011 at 19:10
\$\endgroup\$
1
  • \$\begingroup\$ 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); \$\endgroup\$ Commented May 26, 2011 at 10:19

1 Answer 1

3
\$\begingroup\$

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.

answered Jun 1, 2011 at 11:40
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.