I searched tutorials for parsing response like
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
but no one is posted code about this
.
so,I have implemented parser for this,it is working fine for me
.
In above response the curly brace { } represent object & square bracket [ ] represent array.
Using java Syntax Highlighting
- public JsonParser(String string_Url) {
- java.net.URL url = new java.net.URL(string_Url);
- java.net.URLConnection conn = (java.net.URLConnection) url
- .openConnection();
- conn.setDoOutput(true);
- conn.setDoInput(true);
- String line = Developer
- .convertStreamToString(conn.getInputStream());
- Log.d("RES IS ", line);
- final JSONObject json = new JSONObject(line);
- checkForJSONObject(json);
- }
- /**
- * This is recursive function used for getting key value pair from array or
- * object In this nameArray gives field names & valArray gives contents
- * */
- private void checkForJSONObject(JSONObject jsonObject) {
- try {
- JSONArray nameArray = jsonObject.names();
- JSONArray valArray = jsonObject.toJSONArray(nameArray);
- for (int i = 0; i < jsonObject.length(); i++) {
- // whenever there is array then control comes here
- if (valArray.get(i).getClass().isInstance(new JSONArray())) {
- JSONArray arr = jsonObject.getJSONArray(nameArray.get(i)
- .toString());
- for (int j = 0; j < arr.length(); j++) {
- if (nameArray.get(i).equals("Response")) {
- int_responseCount++;
- System.out.println("**************************** "+int_responseCount);
- }
- Object oo = arr.get(j);
- if (oo.getClass().isInstance(new JSONArray())) {
- System.out.println("IS ARRAY " + arr.get(j));
- } else if (oo.getClass().isInstance(new JSONObject())) {
- checkForJSONObject((JSONObject) oo);
- } else {
- System.out.println("name "
- + nameArray.get(i).toString() + " con "
- + arr.get(j).toString());
- }
- }
- } else if (valArray.get(i).getClass().isInstance(
- new JSONObject())) {
- checkForJSONObject((JSONObject) valArray.get(i));
- } else {
- System.out.println(" NAME " + nameArray.get(i)
- + " CONTENT " + valArray.get(i));
- }
- }
- } catch (Exception e) {
- System.out.println("Ex in checkForJsonObj " + e.toString());
- e.printStackTrace();
- }
- }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4
Any suggestion from u is welcome.
I hope this will helpful for someone.

